#include "ys_form_env.h"
#include "ui_ys_form_env.h"

#include "pub_var.h"
#include "pub_sqthread.h"

#include <QSettings>
#include <QMessageBox>
#include <QSqlError>
#include <QSqlRecord>
#include <QJsonObject>
#include <QJsonDocument>

Form_ys_env::Form_ys_env(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Form_ys_env)
{
    ui->setupUi(this);

    initial_finished = false;  //界面初始化

    //恢复当前窗口位置
    QSettings setIni("clin.ini", QSettings::IniFormat);
    QRect rct = setIni.value("windowState/ys_env").toRect();
    this->setGeometry(rct);
    ui->gb_new_dict->setVisible(false);

    //数据库连接
    qrm = new QSqlQuery(pub::db_m);
    qrmt = new QSqlQuery(pub::db_m);
    qrmt2 = new QSqlQuery(pub::db_m);
    qro = new QSqlQuery(pub::db_o);
    qrot = new QSqlQuery(pub::db_o);

    mdSourceIcd = new QSqlQueryModel;//可选用项目
    mdSourceIcpc = new QSqlQueryModel;//可选用项目
    mdDest = new QSqlQueryModel;//已经选用项目
    mdDest_2 = new QSqlQueryModel;//已经选用项目, 浏览
    mdPop = new QSqlQueryModel;//弹出选择
    mdDict = new QSqlQueryModel;//字典名称列表
    mdValue = new QSqlQueryModel;//字典值

    mdDiag = new QSqlQueryModel;//诊断列表
    mdItem = new QSqlQueryModel;//药品列表
    mdRelated = new QStandardItemModel();//已经对映的诊断和药品
    mdGroup = new QStandardItemModel();//组套
    mdGroupDetail = new QSqlQueryModel;//组套明细

    md_form = new QSqlQueryModel;//剂型
    md_usage = new QSqlQueryModel;//用法
    md_form_usage = new QStandardItemModel();//已经对映的剂型与用法
    md_reci_ck_days = new QSqlQueryModel;//处方限量

    md_diag_med = new QSqlQueryModel;//西医诊断
    md_diag_tr = new QSqlQueryModel;//中医诊断
    md_symptom_tr = new QSqlQueryModel;//中医证候
    md_relate_med_tr = new QSqlQueryModel;//中医诊断与西医诊断关联

    md_drug_for_rule_conflict = new QSqlQueryModel;//
    md_drug_in_rule_conflict = new QSqlQueryModel;//
    md_rule_conflict = new QSqlQueryModel;//

    md_drug_for_rule_constrain = new QSqlQueryModel;//
    md_rule_constrain = new QSqlQueryModel;//

    //IcpcDicType = "0";  //界面初始化时，默认字典为就诊原因

    dlgp = new Pub_pop_get_item;
    dlgp1 = new Pub_pop_delay;
    dlgp1->setModal(true);
    sqth = new sqThread;
    connect( sqth, &sqThread::message, this, &Form_ys_env::threadMsg);

    ui->groupBox_3->setVisible(false);

    ui->tvRelated->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tvGroup->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tvRelated->setExpandsOnDoubleClick(true);
    ui->tvGroup->setExpandsOnDoubleClick(true);

    ui->tabWidget->setCurrentIndex(0);
    ui->tab_recipe_check->setCurrentIndex(0);
    ui->rb01->setChecked(true);
    on_rb01_clicked();


    //sq = "select name from com_dict_com where dic_type='使用单位' ";
    //fillCombo(ui->cbbDoseUnit, sq);//
    sq = "select name from com_dict_com where dic_type='包装单位' ";
    fillCombo(ui->cbbPackUnit, sq);//
    sq = "select name from com_dict_com where dic_type='给药途径' ";
    fillCombo(ui->cbbUsage, sq);//
    sq = "select name from com_dict_com where dic_type='频次' ";
    fillCombo(ui->cbbFreq, sq);//
//    sq = "select a.dept_name from com_department a, com_dict_com b where a.dept_code = b.mark and "
//         " b.dic_type = '执行科室' and b.dept_code = '"+dept_constrain+"'";

    sq = "select name from com_dict_com where dic_type = '执行科室' and dept_code = '"
            + pub::dp_code + "' order by code";

    qDebug()<<"检索执行科室："<<sq;

    fillCombo(ui->cbbExecDept, sq);//执行科室

    sq = "select folder_name from met_com_groupfolder where dept_code = '" + dept_constrain + "' order by folder_ord";
    qro->exec(sq);
    ui->cbbGroupName->clear();
    while(qro->next())
    {
        ui->cbbGroupName->addItem(qro->value(0).toString());
    }
    ui->cbbGroupName->setCurrentIndex(-1);

    item_seq = 100; //药品组套的排序

    sq = "create temporary table if not exists tmp_icpc_ret "
         "(icpc_code varchar(35), "
         "chrgitm_name varchar(100),"
         "chrgitm_code varchar(50),"
         "chrgitm_nat_code varchar(50),"
         "chrgitm_prov_code varchar(30))";
    qrm->exec(sq);

    sq = "create temporary table if not exists tmp_icd_ret"
         " (icd_code varchar(50), "
         "icd_name varchar(100))";
    qrm->exec(sq);

    sq = "create temporary table if not exists tmp_group_detail "
         "(item_code VARCHAR(12) not null unique , "
         "item_name VARCHAR(100) not null,";
    sq += "frequency VARCHAR(20) , "
          "usages VARCHAR(20) , "
          "once_dose decimal(10,3), "
          "dose_unit VARCHAR(16) ,";
    sq += "qty decimal(6) not null, "
          "qty_unit VARCHAR(10) not null, "
          "seq int not null, "
          "item_type char(1) not null,"
          "exe_deptcode varchar(10) not null,"
          "ext_code varchar(5) )";

    if(!qrm->exec(sq))
    {
        QMessageBox::information(this,"note",qrm->lastError().text());
        return;
    }

    //药品配伍冲突临时表
    sq = "create temporary table if not exists tmp_drug_conflict "
         "(drug_name varchar(100) unique, type varchar(10) )";
    qrm->exec(sq);



    noICPC = false;

    //ui->grpGroup->setVisible(false);
    ui->grpFolder->setVisible(false);
    ui->leSpell->setVisible(false);
    ui->lbSpell->setVisible(false);
    ui->leSpell_2->setVisible(false);
    ui->lbSpell_2->setVisible(false);
    ui->toolButton->setVisible(false);
    ui->cbbKey->setVisible(false);
    ui->lbTimes->setVisible(false);
    ui->leTimes->setVisible(false);

    //检查用户是否拥有 医疗基础数据权限
    sq = "select name from com_privileges where role_dept = '医疗基础数据'"
         " and name = '" + pub::usr_name + "'";
    qrm->exec(sq);

    if(qrm->next())
    {
        //有维护权限，可以修改全部
        dept_constrain = "";
        //ui->cbb_dept->setEditable(true);

        sq = "select dept_name, dept_code from com_department "
             " where valid_state = '1' and regdept_flag = '1' ";

        depts_code = pub::fillCombo(ui->cbb_dept, sq, -1);

    }else{
        //无维护权限，只能修改本诊室数据
        dept_constrain = pub::dp_code;
        //ui->cbb_dept->setEditable(false);

        sq = "select dept_name, dept_code from com_department "
             " where valid_state = '1' and regdept_flag = '1' "
             " and dept_code = '" + dept_constrain + "'";

        depts_code = pub::fillCombo(ui->cbb_dept, sq, 0);

        //无维护权限，不可以维护处方限量
        ui->tab_5->setEnabled(false);

    }

    if(ui->cbb_dept->count() < 1)
    {
        QMessageBox::information(this, "注意", "无有效权限！");
        ui->tabWidget->setEnabled(false);
    }

    initial_finished = true;

    qDebug()<<"initial finished, dept code is "<<dept_constrain;

    //ui->cbb_dept->setCurrentText(dept_constrain);

}

Form_ys_env::~Form_ys_env()
{
    delete ui;
}

void Form_ys_env::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    QSettings setIni("clin.ini", QSettings::IniFormat);
    setIni.setValue("windowState/ys_env", QVariant(this->geometry()));
    emit destroyW( "ys_env" );
}

void Form_ys_env::fillCombo(QComboBox *cbb, QString sq )
{
    if(!qrm->exec(sq))
    {
        QMessageBox::information(this, "注意", "检索 comboBox 记录失败！\nerrmsg : " + qrm->lastError().text()+"\nsql : "+sq);
        return;
    }
    cbb->clear();
    while(qrm->next())
    {
        cbb->addItem(qrm->value(0).toString());
    }
    cbb->setCurrentIndex(-1);
}


void Form_ys_env::on_pbSearchS_clicked()
{
    ui->horizontalLayout_26->setStretch(0,3);

    ui->leSpell->setVisible(true);
    ui->lbSpell->setVisible(true);
    ui->leSpell_2->setVisible(false);
    ui->lbSpell_2->setVisible(false);
    ui->toolButton->setVisible(false);

    QStringList sqls;
    sqlMsg.clear();

    if(IcpcDicType == "0")   //就诊原因
    {

        sqls << "mdelete from tmp_icpc_ret";
        sqlMsg << "icpc 清理旧数据。。。";
        QString key = ui->leKeyS_2->text().trimmed();
        if(key.isEmpty())
        {
            //无icpc关键字，使用icd关键字
            key = ui->leKeyS->text().trimmed();
        }

        sq = "minsert into tmp_icpc_ret (icpc_code , chrgitm_name )";
        sq += " select six_code , six_name  "
              " from new_down_1361"
              " where six_name <> '' and six_name like '%";
        sq += key + "%' limit 9999 ";

        sqls << sq;
        sqlMsg << "导入新的 icpc 数据。。。";

        sqth->setSqls(sqls);

        sqth->start();
        dlgp1->setNeedClose(false);
        dlgp1->exec();

        mdSourceIcd->setQuery("");

        sq = "select icpc_code ICPC编码 , chrgitm_name 就诊原因 from tmp_icpc_ret order by convert(chrgitm_name using gbk) ";
        mdSourceIcpc->setQuery(sq, pub::db_m);
        int baseWidth = ui->tvSourceIcpc->width();
        ui->tvSourceIcpc->setModel(mdSourceIcpc);
        pub::setColumnWidth(ui->tvSourceIcpc, "0.4^0.4", baseWidth, 5);

    }

    if(IcpcDicType == "1")   //医疗服务
    {

        sq = "oinsert into sun_tmp_icd(icd_code, icd_name, his_code)"
             " select med_list_codg, "
             //"fixmedins_hilist_name , "
             " case when his_name <> center_name then his_name ||'/'||center_name "
             " else his_name end ,"

             "fixmedins_hilist_id "
             " from fin_com_compare "
             " where list_type = '201'"
             " and (fixmedins_hilist_name like '%%1%' or his_name like '%%1%')"
             " and rownum < 10000";

        sq = sq.arg(ui->leKeyS->text().trimmed());

        sqls << "odelete from sun_tmp_icd";

        sqlMsg << "icd 清理旧数据。。。";
        sqls << sq;
        sqlMsg << "导入新的 icd 数据。。。";
        sqls << "mdelete from tmp_icpc_ret";
        sqlMsg << "icpc 清理旧数据。。。";

        QString key = ui->leKeyS_2->text().trimmed();
        if(key.isEmpty())
        {
            //无icpc关键字，使用icd关键字
            key = ui->leKeyS->text().trimmed();
        }

        sq = "minsert into tmp_icpc_ret (icpc_code , chrgitm_name ,"
             "chrgitm_code, chrgitm_nat_code, chrgitm_prov_code )";
        sq += " select icpc_code, chrgitm_name ,"
              " case when chrgitm_prov_code is null or chrgitm_prov_code = ''  "
              " then chrgitm_nat_code else concat(concat(chrgitm_nat_code,'-'),chrgitm_prov_code) end ,"
              " chrgitm_nat_code, chrgitm_prov_code "
              " from new_down_1362"
              " where chrgitm_attr = '2' and chrgitm_name like ";
        sq += "'%" + key + "%' limit 9999 ";
        sqls << sq;
        sqlMsg << "导入新的 icpc 数据。。。";

        sqth->setSqls(sqls);

        sqth->start();
        dlgp1->setNeedClose(false);
        dlgp1->exec();

        sq = "select icd_code ICD编码, icd_name 项目名称, his_code HIS编码 from sun_tmp_icd order by icd_name ";
        mdSourceIcd->setQuery(sq, pub::db_o);
        int baseWidth = ui->tvSourceIcd->width();
        ui->tvSourceIcd->setModel(mdSourceIcd);
        pub::setColumnWidth(ui->tvSourceIcd, "0.3^0.4^0.2", baseWidth, 5);

        sq = "select icpc_code ICPC编码 , chrgitm_name 项目名称, chrgitm_code ICD编码,"
             " chrgitm_nat_code, chrgitm_prov_code"
             " from tmp_icpc_ret order by convert(chrgitm_name using gbk) ";
        mdSourceIcpc->setQuery(sq, pub::db_m);
        baseWidth = ui->tvSourceIcpc->width();
        ui->tvSourceIcpc->setModel(mdSourceIcpc);
        pub::setColumnWidth(ui->tvSourceIcpc, "0.2^0.3^0.4^0^0", baseWidth, 5);
    }

    if(IcpcDicType == "2")   //诊断结果
    {

        sq = "minsert into tmp_icd_ret (  icd_code  ,  icd_name )";
        sq += " select 诊断代码, 诊断名称  from new_down_1307"
              " where 诊断代码 not in ('','null') and  诊断名称  not in ('','null') "
              " and 诊断名称 like '%" + ui->leKeyS->text().trimmed() + "%' limit 9999";

        sqls << "mdelete from tmp_icd_ret";
        sqlMsg << "icd 清理旧数据。。。";
        sqls << sq;
        sqlMsg << "导入新的 icd 数据。。。";
        sqls << "mdelete from tmp_icpc_ret";
        sqlMsg << "icpc 清理旧数据。。。";

        QString key = ui->leKeyS_2->text().trimmed();
        if(key.isEmpty())
        {
            //无icpc关键字，使用icd关键字
            key = ui->leKeyS->text().trimmed();
        }
        sq = "minsert into tmp_icpc_ret (icpc_code , chrgitm_name )";
        sq += " select six_code , ( case when six_name is null then icd10_asoc_name else six_name  end)  "
              " from new_down_1361 "
              " where icd10_asoc_name like '%" + key + "%'";
        sq += " or six_name like '%" + key + "%' limit 9999";
        sqls << sq;
        sqlMsg << "导入新的 icpc 数据。。。";

        sqth->setSqls(sqls);

        sqth->start();
        dlgp1->setNeedClose(false);
        dlgp1->exec();

        sq = "select icd_code ICD编码, icd_name 诊断名称 from tmp_icd_ret order by convert(icd_name using gbk) ";
        mdSourceIcd->setQuery(sq, pub::db_m);
        int baseWidth = ui->tvSourceIcd->width();
        ui->tvSourceIcd->setModel(mdSourceIcd);
        pub::setColumnWidth(ui->tvSourceIcd, "0.4^0.4", baseWidth, 5);

        sq = "select icpc_code ICPC编码, chrgitm_name 诊断名称 "
             " from tmp_icpc_ret order by convert(chrgitm_name using gbk) ";
        mdSourceIcpc->setQuery(sq, pub::db_m);
        baseWidth = ui->tvSourceIcpc->width();
        ui->tvSourceIcpc->setModel(mdSourceIcpc);
        pub::setColumnWidth(ui->tvSourceIcpc, "0.4^0.4", baseWidth, 5);

    }

    if(IcpcDicType == "3")   //药品
    {
        if(ui->rbCompared->isChecked())
        {
            sq = "oinsert into sun_tmp_icd(icd_code, icd_name, his_code, his_specs)"
                 //" (select med_list_codg, "
                 //" case when his_name <> center_name then his_name ||'/'||center_name "
                 //" else his_name end ,"
                 " (select med_list_codg, his_name, "
                 " fixmedins_hilist_id , substr(his_specs, 1, 18) "
                 " from fin_com_compare"
                 " where list_type in ( '103','102','101') "
                 " and (fixmedins_hilist_name like '%%1%' or his_name like '%%1%')"
                 " and rownum < 10000)";

            sq = sq.arg(ui->leKeyS->text().trimmed());

        }
        else
        {
            sq = "oinsert into sun_tmp_icd(icd_code, icd_name, his_code, his_specs )";
            sq += " (select (select med_list_codg from fin_com_compare b where b.fixmedins_hilist_id = a.drug_code), ";
            sq += " a.trade_name,a.drug_code, substr(a.specs, 1, 18) from pha_com_baseinfo a  ";
            sq += " where trade_name like '%" + ui->leKeyS->text().trimmed() + "%' and rownum < 10000)";
        }

        qDebug()<<"向临时表导入药品数据："<<sq;
        sqls << "odelete from sun_tmp_icd";
        sqlMsg << "icd 清理旧数据。。。";
        sqls << sq;
        sqlMsg << "导入新的 icd 数据。。。";
        sqls << "mdelete from tmp_icpc_ret";
        sqlMsg << "icpc 清理旧数据。。。";

        QString key = ui->leKeyS_2->text().trimmed();
        if(key.isEmpty())
        {
            //无icpc关键字，使用icd关键字
            key = ui->leKeyS->text().trimmed();
        }

        sq = "minsert into tmp_icpc_ret (icpc_code , chrgitm_name ,"
             "chrgitm_code, chrgitm_nat_code, chrgitm_prov_code )"
             " select icpc_code, chrgitm_name ,"
             " case when chrgitm_prov_code is null or chrgitm_prov_code = ''  "
             " then chrgitm_nat_code else concat(concat(chrgitm_nat_code,'-'),chrgitm_prov_code) end ,"
             " chrgitm_nat_code, chrgitm_prov_code "
             " from new_down_1362 "
             " where chrgitm_attr = '1' and chrgitm_name like '%" + key + "%' limit 9999";
        sqls << sq;
        sqlMsg << "导入新的 icpc 数据。。。";

        sqth->setSqls(sqls);

        sqth->start();

        dlgp1->setNeedClose(false);
        dlgp1->exec();

        sq = "select icd_code ICD编码, icd_name 项目名称, his_code HIS编码, his_specs 规格 from sun_tmp_icd order by icd_name ";
        mdSourceIcd->setQuery(sq, pub::db_o);

        int baseWidth = ui->tvSourceIcd->width();
        ui->tvSourceIcd->setModel(mdSourceIcd);

        pub::setColumnWidth(ui->tvSourceIcd, "0.3^0.3^0.15^0.15", baseWidth, 5);

        sq = "select icpc_code ICPC编码 , chrgitm_name 项目名称, chrgitm_nat_code ICD编码,"
             " chrgitm_nat_code, chrgitm_prov_code "
             " from tmp_icpc_ret order by convert(chrgitm_name using gbk) ";
        mdSourceIcpc->setQuery(sq, pub::db_m);

        baseWidth = ui->tvSourceIcpc->width();
        ui->tvSourceIcpc->setModel(mdSourceIcpc);

        pub::setColumnWidth(ui->tvSourceIcpc, "0.15^0.35^0.3^0^0", baseWidth, 5);

    }

    if(IcpcDicType == "8" || IcpcDicType == "9")   //中医诊断, 证候
    {
        sqls << "mdelete from tmp_icd_ret";
        sqlMsg << "icd 清理旧数据。。。";

        sq = "minsert into tmp_icd_ret (  icd_code  ,  icd_name )";
        if(IcpcDicType == "8")
        {
        sq += " select 疾病分类代码, 疾病分类名称 from new_down_1314"
              " where "// 诊断代码 not in ('','null') and  诊断名称  not in ('','null') and "
              " 疾病分类名称 like '%" + ui->leKeyS->text().trimmed() + "%' limit 9999";
        }

        if(IcpcDicType == "9")
        {
        sq += " select 证候分类代码, 证候分类名称 from new_down_1315"
              " where "// 诊断代码 not in ('','null') and  诊断名称  not in ('','null') and "
              " 证候分类名称 like '%" + ui->leKeyS->text().trimmed() + "%' limit 9999";
        }

        sqls << sq;
        sqlMsg << "导入新的 icd 数据。。。";

        sqlMsg << "发生错误，正在回滚数据。。。";

        sqth->setSqls(sqls);

        sqth->start();
        dlgp1->setNeedClose(false);
        dlgp1->exec();

        sq = "select icd_code ICD编码, icd_name 中医诊断名称 from tmp_icd_ret order by convert(icd_name using gbk) ";
        mdSourceIcd->setQuery(sq, pub::db_m);
        int baseWidth = ui->tvSourceIcd->width();
        ui->tvSourceIcd->setModel(mdSourceIcd);
        pub::setColumnWidth(ui->tvSourceIcd, "0.4^0.4", baseWidth, 5);


    }


    //ui->leKeyS->clear();
}

void Form_ys_env::on_pbSearchD_clicked()
{

    if(ui->cbb_dept->currentText().isEmpty())
    {
        QMessageBox::information(this, "注意", "未指定当前诊室，请谨慎操作！");
        //return;
    }
    ui->horizontalLayout_26->setStretch(0,0);
    ui->leSpell->setVisible(false);
    ui->lbSpell->setVisible(false);
    ui->leSpell_2->setVisible(true);
    ui->lbSpell_2->setVisible(true);
    ui->toolButton->setVisible(true);
    qApp->processEvents();

    if(IcpcDicType == "3" ||IcpcDicType == "1" )  //
    {
        sq = "select a.item_name 项目名称,  a.nat_code icd编码, '-',a.icpc_code icpc编码,"
             " a.item_code his编码, a.dept_code, a.atinc, a.py 拼音码"
             " from com_dict_icpc a where a.type = '" + IcpcDicType + "' and a.item_name like '%";
        sq += ui->leKeyD->text().trimmed() + "%'";
        sq += " and instr(a.dept_code, '" + dept_constrain + "' ) > 0 order by convert(a.item_name using gbk)";
        mdDest->setQuery(sq, pub::db_m);
        ui->tvDest->setModel(mdDest);
        qDebug()<<sq;
        int baseWidth = ui->tvDest->width();
        pub::setColumnWidth(ui->tvDest, "0.25^0.1^0.25^0.2^0^0^0^0.1", baseWidth, 10);

    }
    else    //
    {
        sq = "select a.item_name icd名称, a.nat_code icd编码, a.icpc_name icpc名称, a.icpc_code icpc编码,"
             " '-', a.dept_code, a.atinc, a.py 拼音码"
             " from com_dict_icpc a"
             " where a.type = '" + IcpcDicType + "' and a.item_name like '%";
        sq += ui->leKeyD->text().trimmed() + "%'";
        sq += " and instr(a.dept_code, '" + dept_constrain + "' ) > 0 order by convert(a.item_name using gbk) ";
        mdDest->setQuery(sq, pub::db_m);
        ui->tvDest->setModel(mdDest);
        qDebug()<<sq;
        int baseWidth = ui->tvDest->width();
        pub::setColumnWidth(ui->tvDest, "0.25^0.15^0.25^0.15^0^0^0^0.1", baseWidth, 10);
    }
    qDebug()<<sq;
}

void Form_ys_env::on_tbAdd_clicked()
{

   if(ui->cbb_dept->currentText().isEmpty())
   {
       //QMessageBox::information(this, "注意", "未选定当前诊室！");
       QMessageBox::StandardButtons bt;
       bt = QMessageBox::question(this, "注意", "未选定目标诊室，是否继续？");
       if(bt != QMessageBox::Yes)
       {
           return;
       }

   }
    //if(!noICPC && !ui->tvSourceIcpc->currentIndex().isValid())
    if(!ui->ckb_no_icpc->isChecked() && !ui->tvSourceIcpc->currentIndex().isValid())
    {
        //非忽略icpc情况下，icpc项目必须选择。
        QMessageBox::information(this, "注意", "未选定有效数据行！");
        return;
    }
    if(IcpcDicType == "1" //化验检查
            || IcpcDicType == "2" //西医诊断
            || IcpcDicType == "3" //治疗处置
            || IcpcDicType == "8" //中医诊断
            || IcpcDicType == "9" //中医证候
            )
    {
        if(!ui->tvSourceIcd->currentIndex().isValid())
        {
            QMessageBox::information(this, "注意", "未选定有效数据行！");
            return;
        }
    }

    QString  item_name, his_code, icpc_code, icpc_name, icd_code0, icd_code1;
    item_name = ui->tvSourceIcd->currentIndex().siblingAtColumn(1).data(0).toString().trimmed();
    if(item_name.isEmpty()){
        item_name = ui->tvSourceIcpc->currentIndex().siblingAtColumn(1).data(0).toString().trimmed();
    }
    icd_code0 = ui->tvSourceIcd->currentIndex().siblingAtColumn(0).data(0).toString().trimmed();

    if(IcpcDicType == "8" || IcpcDicType == "9") //中医诊断 中医证候
    {
        his_code = ui->tvSourceIcd->currentIndex().siblingAtColumn(0).data(0).toString().trimmed();
    }
    else
    {
        his_code = ui->tvSourceIcd->currentIndex().siblingAtColumn(2).data(0).toString().trimmed();
    }

qDebug()<< "his_code,icd_code0 "<< his_code<<","<<icd_code0;
    if(ui->ckb_no_icpc->isChecked())
    {
        icpc_code = "0";
        icd_code1 = icd_code0;
    }else{
        icpc_code = ui->tvSourceIcpc->currentIndex().siblingAtColumn(0).data(0).toString().trimmed();
        icpc_name = ui->tvSourceIcpc->currentIndex().siblingAtColumn(1).data(0).toString().trimmed();
        QStringList icds;
        icds << ui->tvSourceIcpc->currentIndex().siblingAtColumn(2).data(0).toString().trimmed();
        icds << ui->tvSourceIcpc->currentIndex().siblingAtColumn(3).data(0).toString().trimmed();
        icds << ui->tvSourceIcpc->currentIndex().siblingAtColumn(4).data(0).toString().trimmed();

        //医保早期和后期数据格式不一致，有用省码，有用国码+省码
        //所以这里能匹配哪一个都可以

        if(icds.indexOf(icd_code0) > -1)
        {
            icd_code1 = icd_code0 ;
        }
        else
        {
            icd_code1 = "no_icd_code";
        }

    }

    if(IcpcDicType == "3" || IcpcDicType == "1" )  //检查选择项目是否匹配
    {
        QMessageBox::StandardButton result;
        if(icd_code0 != icd_code1)
        {
            result = QMessageBox::information(this, "注意",
                                              "icd 目录选项与 icpc 目录选项不匹配！是否强制关联？",
                                              QMessageBox::Yes|QMessageBox::No);
            if(result == QMessageBox::No)
            {
                return;
            }
        }
    }

    //检查记录是否已经存在
    sq = "select dept_code from com_dict_icpc where type = '" + IcpcDicType + "' ";
    sq += " and item_code = '" + his_code + "' and icpc_code = '" + icpc_code + "'";
    if(!qrm->exec(sq))
    {
        QMessageBox::information(this, "注意", "检索记录失败！\nerrmsg : " + qrm->lastError().text()+"\nsql : "+sq);
        return;
    }

    if(IcpcDicType == "8" || IcpcDicType == "9")
    {
        int pos = item_name.indexOf("(可选词");
        if(pos > 0)
        {
            item_name = item_name.left( pos );
        }

    }

    if(qrm->next())
    {
        //记录存在，检查科室标志是否存在
        QString dp = qrm->value(0).toString();
        if(dp.contains(dept_constrain))
        {
            //记录存在，科室存在，无需保存
            QMessageBox::information(this, "注意", "数据已经存在，不需要再次保存！");
        }
        else
        {
            dp += dept_constrain + "^";
            sq = "update com_dict_icpc set dept_code ='" + dp + "', icpc_code = '" + icpc_code + "', ";
            sq += " nat_code = '" + icd_code0 + "',";   //nat_code 因为医保对照原因，可能会变更
            sq += " py = '" + ui->leSpell->text().trimmed().toUpper() + "'";
            sq += " where type = '" + IcpcDicType + "' and item_name = '" + item_name + "'";
            qrm->exec(sq);
            QMessageBox::information(this, "注意", "数据更新成功！");
        }
        return;
    }

    //记录不存在，插入新记录

    sq = " insert into com_dict_icpc "
         " (icpc_code,icpc_name,item_code,nat_code,item_name,oper_code,oper_date,valid_flag,type,dept_code,py)"
         " values ('";
    sq += icpc_code + "','" + icpc_name + "','" + his_code + "','" + icd_code0 + "','" + item_name + "','";
    sq += pub::usr_code + "', curdate(),'1','" + IcpcDicType + "','";
    sq += dept_constrain + "^','";
    sq += ui->leSpell->text().trimmed().toUpper() + "')";

    qDebug()<<"com_dict_icpc 插入新记录 : " <<sq;

    if(qrm->exec(sq))
    {
        QMessageBox::information(this, "注意", "数据保存成功！");
    }
    else
    {
        QMessageBox::information(this, "注意", "数据保存失败！\nerrmsg : " + qrm->lastError().text()+"\nsql : "+sq);
        qDebug()<<"sql error. \n"<< qrm->lastError().text() << "\n"<< sq;
    }
    ui->leKeyS->clear();
    ui->leKeyS_2->clear();
    ui->leSpell->clear();
    //ui->ckb_no_icpc->setChecked(false);
}

void Form_ys_env::on_tbRemove_clicked()
{
    if(!ui->tvDest->currentIndex().isValid())
    {
        QMessageBox::information(this, "注意", "未选定有效数据行！");
        return;
    }

    bool remove_all = false;
    if(ui->cbb_dept->currentText().isEmpty())
    {
        QMessageBox::StandardButtons bt;
        bt = QMessageBox::question(this, "注意", "未指定目标诊室，即将删除项目关联的所有诊室信息，是否继续？");
        if(bt != QMessageBox::Yes)
        {
            return;
        }

        remove_all = true;
    }

    QString icpc_code, icd_code, name, dept;

    name = ui->tvDest->currentIndex().siblingAtColumn(0).data(0).toString();
    icpc_code = ui->tvDest->currentIndex().siblingAtColumn(3).data(0).toString();
    icd_code = ui->tvDest->currentIndex().siblingAtColumn(1).data(0).toString();
    dept = ui->tvDest->currentIndex().siblingAtColumn(5).data(0).toString();

    if(remove_all || dept == dept_constrain + "^")  //项目仅有一个科室标志，删除记录
    {
        sq = "delete from com_dict_icpc where type = '" + IcpcDicType + "' and item_name = '" + name + "'";
        sq += " and icpc_code = '"+icpc_code+"' and nat_code = '" + icd_code + "'";
    }
    else    //项目具有多个科室标志，移除科室标志
    {
        dept.replace(dept_constrain + "^", "");
        sq = "update com_dict_icpc set dept_code = '" + dept + "' where  type = '" + IcpcDicType + "' ";
        sq += " and item_name = '" + name + "' and icpc_code = '"+icpc_code+"' and nat_code = '" + icd_code + "'";
    }

    if(qrm->exec(sq))
    {
        QMessageBox::information(this, "注意", name + " 删除成功！");
    }
    else
    {
        QMessageBox::information(this, "注意", "删除失败！\nerrmsg : "
                                 + qrm->lastError().text()+"\nsql : "+sq);
    }
}

void Form_ys_env::on_rb01_clicked()
{
    mdSourceIcd->setQuery("");
    mdSourceIcpc->setQuery("");
    mdDest->setQuery("");
    ui->leKeyS->clear();
    ui->leKeyS_2->clear();
    ui->ckb_no_icpc->setChecked(false);
    ui->ckb_no_icpc->setEnabled(true);
    ui->tvSourceIcd->setVisible(true);
    ui->tvSourceIcpc->setVisible(true);

    if(ui->rb01->isChecked())   //就诊原因
    {
        IcpcDicType = "0";
        ui->tvSourceIcd->setVisible(false);
        ui->groupBox_3->setVisible(false);
    }
    else if(ui->rb02->isChecked())    //检查化验，非药物治疗，各种处置
    {
        IcpcDicType = "1";
        ui->groupBox_3->setVisible(false);
    }
    else if(ui->rb03->isChecked())   //诊断结果
    {
        IcpcDicType = "2";
        ui->groupBox_3->setVisible(false);
    }
    else if(ui->rb04->isChecked())    //药物治疗
    {
        IcpcDicType = "3";
        ui->groupBox_3->setVisible(true);
    }
    else if(ui->rb_tr_symptom->isChecked() || ui->rb_tr_diag->isChecked())    //中医
    {
        ui->ckb_no_icpc->setChecked(true);
        ui->ckb_no_icpc->setEnabled(false);
        ui->tvSourceIcpc->setVisible(false);

        if(ui->rb_tr_symptom->isChecked())
        {
            IcpcDicType = "9";  //中医症候
        }
        if(ui->rb_tr_diag->isChecked())
        {
            IcpcDicType = "8";  //中医诊断
        }
        ui->groupBox_3->setVisible(false);
    }
}

void Form_ys_env::on_rb02_clicked()
{
    on_rb01_clicked();
}

void Form_ys_env::on_rb03_clicked()
{
    on_rb01_clicked();
}

void Form_ys_env::on_rb04_clicked()
{
    on_rb01_clicked();
}

void Form_ys_env::on_pbFresh_clicked()
{
    QString tmp = (ui->rbDoct->isChecked() ? "doct_dic" : "com_dic");

    sq = "select name 字典列表, mark from com_dict_com where dic_type = '"
            + tmp + "' order by convert(name using gbk)";

    mdDict->setQuery(sq, pub::db_m);
    ui->tvDict->setModel(mdDict);

    int width = ui->tvDict->width();
    ui->tvDict->setColumnWidth(0, width * 0.85);
    ui->tvDict->setColumnHidden(1,true);
}

void Form_ys_env::on_pbExit_clicked()
{
    close();
}


void Form_ys_env::on_tvDict_doubleClicked(const QModelIndex &index)
{
    on_tvDict_clicked(index);
}

void Form_ys_env::on_tvDict_clicked(const QModelIndex &index)
{
    mdidx = index;
    QString dicName = index.siblingAtColumn(0).data(0).toString(); //当前字典名称
    dicMode = index.siblingAtColumn(1).data(0).toString();

    if(dicName == "执行科室")
    {
        //执行科室 'T'医技, 'C'门诊, 'P'药房, 'N'护士站
        sq = "select dept_name from com_department where valid_state = '1' and dept_type in('T','C','P','N')";
        fillCombo(ui->cbbKey, sq);

        //ui->lbName1->setVisible(true);
        ui->cbbKey->setVisible(true);
        //ui->lbName0->setVisible(false);
        ui->leKey->setVisible(false);
    }
    else
    {
        //ui->lbName0->setVisible(false);
        ui->cbbKey->setVisible(false);
        //ui->lbName1->setVisible(true);
        ui->leKey->setVisible(true);
    }

    if(dicName == "频次")
    {
        ui->lbTimes->setVisible(true);
        ui->leTimes->setVisible(true);
    }
    else
    {
        ui->lbTimes->setVisible(false);
        ui->leTimes->setVisible(false);
    }

    ui->leDict->setText(dicName);
    QModelIndex idx = QModelIndex();
    on_tvValue_clicked(idx);

    QString tmp = (ui->rbDoct->isChecked() ? "doct" : "com");
    sq = "select name 键值, code 代码 , dept_code , ord "
         " from com_dict_com where mark = '"+tmp+"' and dic_type = '"+dicName+"' ";
    if(dicMode == "dept")
    {
        sq += " and dept_code = '"+dept_constrain+"'";
    }

    if(ui->rbCode->isChecked())
    {
        sq += " order by code";
    }else{
        sq += " order by convert(name using gbk)";
    }

    mdValue->setQuery(sq, pub::db_m);

    ui->tvValue->setModel(mdValue);

    pub::setColumnWidth(ui->tvValue, "0.4^0.4", ui->tvValue->width(), 5 );
    //ui->tvValue->setColumnWidth(0, width * 0.4);
    //ui->tvValue->setColumnWidth(1, width * 0.4);
    //ui->tvValue->setColumnWidth(2, 0);

}

void Form_ys_env::on_tvValue_doubleClicked(const QModelIndex &index)
{
    on_tvValue_clicked(index);
}

void Form_ys_env::on_tvValue_clicked(const QModelIndex &index)
{
    QString key = index.siblingAtColumn(0).data(0).toString();
    QString code = index.siblingAtColumn(1).data(0).toString();
    QString times = index.siblingAtColumn(2).data(0).toString();
    QString ord = index.siblingAtColumn(3).data(0).toString();
    ui->cbbKey->setCurrentText(key);
    ui->leKey->setText(key);
    ui->leCode->setText(code);
    ui->leTimes->setText(times);
    ui->leOrd->setText(ord);

}

void Form_ys_env::on_pbAdd_clicked()
{
    if(ui->leDict->text().trimmed().isEmpty())
    {
        QMessageBox::information(this, "注意", "字典类别不允许空缺！");
        return;
    }

    if(ui->leKey->text().trimmed().isEmpty() || ui->leCode->text().trimmed().isEmpty())
    {
        QMessageBox::information(this, "注意", "字典值不允许空缺！");
        return;
    }

    if(ui->leDict->text() == "频次" && ui->leTimes->text().trimmed().isEmpty())
    {
        QMessageBox::information(this, "注意", "频次数量值不允许空缺！");
        return;
    }

    if(ui->leDict->text() == "频次" && qFuzzyCompare(0, ui->leTimes->text().toDouble()))
    {
        QMessageBox::information(this, "注意", "频次数量值无效！");
        return;
    }

    sq = "insert into com_dict_com (dic_type, name, code, dept_code,"
         " oper_code, oper_time, valid_flag, ord, mark) values('";
    sq += ui->leDict->text() + "','";
    sq += ui->leKey->text().trimmed() + "','";
    sq += ui->leCode->text().trimmed() + "','";

    if(ui->leDict->text() == "频次" )
    {
        sq += ui->leTimes->text() + "','";
    }
    else
    {
        if(dicMode == "dept"){
            sq += dept_constrain + "','";
        }else{
            sq += "','";
        }
    }

    QString tmp = (ui->rbDoct->isChecked() ? "doct" : "com");
    sq += pub::usr_code + "', now(), '1', " + QString::number(ui->leOrd->text().toInt()) ;
    sq += ", '" + tmp + "')";

    qDebug()<<"插入字典数据："<<sq;
    if(qrm->exec(sq))
    {
        QModelIndex idx = QModelIndex();
        on_tvValue_clicked(idx);
    }
    else
    {
        QMessageBox::information(this, "注意", "插入失败，请检查数据是否重复？");
        return;
    }
    on_tvDict_clicked(mdidx);
    QModelIndex idx = QModelIndex();
    on_tvValue_clicked(idx);
}

void Form_ys_env::on_pbDel_clicked()
{
    if(ui->leDict->text().trimmed().isEmpty())
    {
        QMessageBox::information(this, "注意", "字典类别不允许空缺！");
        return;
    }
    if(ui->leKey->text().trimmed().isEmpty() || ui->leCode->text().trimmed().isEmpty())
    {
        QMessageBox::information(this, "注意", "字典值不允许空缺！");
        return;
    }
    sq = "delete from com_dict_com where ";
    sq += " dic_type = '"+ui->leDict->text()+"'";
    sq += " and name = '"+ui->leKey->text().trimmed()+"' ";
    sq += " and code = '"+ui->leCode->text().trimmed()+"' ";

    QString tmp = (ui->rbDoct->isChecked() ? "doct" : "com");

    sq += " and mark = '"+tmp+"'";
    if(dicMode == "dept"){
        sq += " and dept_code = '"+dept_constrain+"' ";
    }

    if(qrm->exec(sq)){
        QMessageBox::information(this, "注意", "删除操作成功！");
    }
    on_tvDict_clicked(mdidx);
    QModelIndex idx = QModelIndex();
    on_tvValue_clicked(idx);
}

void Form_ys_env::on_rbKey_clicked()
{
    on_rbCode_clicked();
}

void Form_ys_env::on_rbCode_clicked()
{
    if(ui->rbDoct->isChecked())
    {
        sq = "select name 键值, code 代码 from com_dict_com where mark = 'doct' and dic_type = '"+ui->leDict->text()+"' ";
    }
    else
    {
        sq = "select name 键值, code 代码 from com_dict_com where mark = 'com' and dic_type = '"+ui->leDict->text()+"' ";
    }
    if(dicMode == "dept")
    {
        sq += " and dept_code = '"+dept_constrain+"'";
    }

    if(ui->rbCode->isChecked())
    {
        sq += " order by code";
    }else{
        sq += " order by convert(name using gbk)";

    }

    mdValue->setQuery(sq, pub::db_m);

    ui->tvValue->setModel(mdValue);

    int width = ui->tvValue->width();
    ui->tvValue->setColumnWidth(0, width * 0.4);
    ui->tvValue->setColumnWidth(1, width * 0.4);

}

void Form_ys_env::on_pbSearchDiag_clicked()
{
    sq = "select item_name 诊断名称,icpc_code,nat_code,item_code from com_dict_icpc "
         " where valid_flag = '1' and  type in('1', '2') "
         " and instr(dept_code , '"+ dept_constrain +"')";
    sq += " and item_name like '%";
    sq += ui->leKeyDiag->text().trimmed() + "%' order by convert(item_name using gbk) ";

    mdDiag->setQuery(sq, pub::db_m);
    ui->tvDiag->setModel(mdDiag);

    int width = ui->tvDiag->width();
    pub::setColumnWidth(ui->tvDiag, "0.85", width, 10);
}

void Form_ys_env::on_pbSearchItem_clicked()
{
    sq = "select distinct item_name 药品 from com_dict_icpc " //,icpc_code,nat_code,item_code
         " where valid_flag = '1' and  type = '3' "
         " and instr(dept_code , '"+ dept_constrain +"')";
    sq += " and item_name like '%";
    sq += ui->leKeyItem->text().trimmed() + "%' order by convert(item_name using gbk) ";

    mdItem->setQuery(sq, pub::db_m);
    ui->tvItem->setModel(mdItem);

    int width = ui->tvItem->width();
    pub::setColumnWidth(ui->tvItem, "0.85^0", width, 10);

}

void Form_ys_env::saveDiagItem()
{
    //保存关联关系  insert
    sq = "replace into reci_ck_diag_drug (diag_name,diag_code_icpc,diag_code_nat,item_name,dept_code,"
         "oper_code,oper_date, amount_limit, amount_unit) values (";
    sq += "'" + ui->tvDiag->currentIndex().siblingAtColumn(0).data(0).toString().trimmed() + "',";
    sq += "'" + ui->tvDiag->currentIndex().siblingAtColumn(1).data(0).toString().trimmed() + "',";
    sq += "'" + ui->tvDiag->currentIndex().siblingAtColumn(2).data(0).toString().trimmed() + "',";
    sq += "'" + ui->tvItem->currentIndex().siblingAtColumn(0).data(0).toString().trimmed() + "',";
    sq += "'"+dept_constrain+"','"+pub::usr_code+"', now(),";
    sq += ui->le_limit_amount->text() + ",'" + ui->le_baseunit->text() + "')";
    qDebug()<<"保存诊断与药品关联："<<sq;
    if(!qrm->exec(sq))
    {
        QMessageBox::information(this, "注意", "保存失败！\n" + qrm->lastError().text());
        return;
    }

    if(qrm->numRowsAffected() > 1)
    {
        //有重复数据项
        QMessageBox::information(this, "注意", "数据已经保存，关联列表内容将在刷新后正确显示！" );
        return;
    }

    QString diag, item; //诊断，药品
    diag = ui->tvDiag->currentIndex().siblingAtColumn(0).data(0).toString().trimmed();
    item = ui->tvItem->currentIndex().siblingAtColumn(0).data(0).toString().trimmed();

    //检索父级项目是否已经存在
    QStandardItem * itm ;
    bool found = false;
    for(int i = 0; i< mdRelated->rowCount(); i++)
    {
        itm = mdRelated->item(i,0);
        QString it = itm->text();

        if( it== diag || it == item)
        {
            //诊断名称和药品名称不可能相同，不管是诊断关联药品还是药品关联诊断，都按同一逻辑进行判断。
            found = true;
            break;
        }
    }

    QStandardItem *itemparent, *itemChild, *limit_amount, *limit_unit;

    limit_amount = new QStandardItem(ui->le_limit_amount->text());
    limit_unit = new QStandardItem(ui->le_baseunit->text());

    if(found)
    {
        //存在父级记录，直接添加子记录
        if(ui->rbD2I->isChecked())
        {
            //诊断关联药品
            itemChild = new QStandardItem(item);
            itm->appendRow({itemChild, limit_amount, limit_unit});
        }
        else
        {
            //药品关联诊断
            itemChild = new QStandardItem(diag);
            itm->appendRow({itemChild, limit_amount, limit_unit});
        }
    }
    else
    {
        //父级记录不存在，新建父级记录，再添加子记录
        if(ui->rbD2I->isChecked())
        {
            itemparent = new QStandardItem(diag);
            itemChild = new QStandardItem(item);
        }
        else
        {
            itemparent = new QStandardItem(item);
            itemChild = new QStandardItem(diag);
        }
        itemparent->appendRow(itemChild);
        mdRelated->appendRow(itemparent);

    }
}


void Form_ys_env::on_tbAdd_2_clicked()
{
    //if(!ui->tvDiag->currentIndex().isValid() || !ui->tvItem->currentIndex().isValid())
    if(ui->le_diag_name_drug->text().isEmpty()
            || ui->le_drug_name_diag->text().isEmpty())
    {
        QMessageBox::information(this, "注意", "未选定有效数据行！");
        return;
    }
    if(ui->le_limit_amount->text().isEmpty())// '基本剂量';
    {
        QMessageBox::information(this, "注意", "剂量不可以空白！");
        ui->le_limit_amount->setFocus();
        return ;
    }
    else
    {
        double test_double = ui->le_limit_amount->text().toDouble();
        if(test_double < 0 || qFuzzyCompare(test_double, 0))
        {
            QMessageBox::information(this, "注意", "剂量数值无效！");
            ui->le_limit_amount->setFocus();
            return ;
        }
    }

    saveDiagItem();
}


void Form_ys_env::on_tvDiag_doubleClicked(const QModelIndex &index)
{
    Q_UNUSED(index)
    /*
    if( !ui->tvItem->currentIndex().isValid())
    {
        QMessageBox::information(this, "注意", "未选定有效的药品！");
        return;
    }
    if(ui->le_limit_amount->text().isEmpty())// '基本剂量';
    {
        QMessageBox::information(this, "注意", "剂量不可以空白！");
        ui->le_limit_amount->setFocus();
        return ;
    }
    else
    {
        double test_double = ui->le_limit_amount->text().toDouble();
        if(test_double < 0 || qFuzzyCompare(test_double, 0))
        {
            QMessageBox::information(this, "注意", "剂量数值无效！");
            ui->le_limit_amount->setFocus();
            return ;
        }
    }
    saveDiagItem();
    */
}

void Form_ys_env::on_tvItem_doubleClicked(const QModelIndex &index)
{
    Q_UNUSED(index)
    //if(!ui->tvDiag->currentIndex().isValid())
    //{
    //    QMessageBox::information(this, "注意", "未选定有效的诊断！");
    //    return;
    //}
    //saveDiagItem();
}

void Form_ys_env::on_pbSearchRelated_clicked()
{

    QStringList title;
    mdRelated->clear();

    if(ui->rbD2I->isChecked())
    {
        title << "诊断->用药"<<"日限量"<<"单位";
        sq = "select  diag_name 诊断, item_name 药品 , amount_limit, amount_unit "
             " from reci_ck_diag_drug  where dept_code = '" + dept_constrain + "'";
        sq += " and item_name like '%" + ui->leKeyRelated->text().trimmed() + "%' order by convert(diag_name using gbk) ";

    }else{
        title << "用药->诊断"<<"日限量"<<"单位";
        sq = "select  item_name 药品, diag_name 诊断 , amount_limit, amount_unit "
             " from reci_ck_diag_drug  where dept_code = '" + dept_constrain + "'";
        sq += " and item_name like '%" + ui->leKeyRelated->text().trimmed() + "%' order by convert(item_name using gbk) ";

    }

    QStandardItem *items, *it_tmp, *limit_amount, *limit_unit;

    qrm->exec(sq);
    QString prev,cur;   //用于标记项目名称变化
    qrm->next();
    prev = qrm->value(0).toString();
    items =  new QStandardItem( qrm->value(0).toString());
    it_tmp = new QStandardItem( qrm->value(1).toString());
    limit_amount = new QStandardItem( qrm->value(2).toString());
    limit_unit = new QStandardItem( qrm->value(3).toString());
    items->appendRow({it_tmp, limit_amount, limit_unit});

    while (true)
    {
        if(!qrm->next())
        {
            mdRelated->appendRow(items);
            break;
        }
        cur = qrm->value(0).toString();

        if( prev != cur)
        {
            mdRelated->appendRow(items);
            items = new QStandardItem(cur);
            prev = cur;
        }

        it_tmp = new QStandardItem( qrm->value(1).toString());
        limit_amount = new QStandardItem( qrm->value(2).toString());
        limit_unit = new QStandardItem( qrm->value(3).toString());

        items->appendRow({it_tmp, limit_amount, limit_unit});

    }

    mdRelated->setHorizontalHeaderLabels(title);
    ui->tvRelated->setModel(mdRelated);
    int w = ui->tvRelated->width();
    ui->tvRelated->setColumnWidth(0, w * 0.4);
    ui->tvRelated->setColumnWidth(1, w * 0.15);
    ui->tvRelated->setColumnWidth(2, w * 0.15);

}

void Form_ys_env::on_tbRemove_2_clicked()
{
    QModelIndex currentindex = ui->tvRelated->currentIndex();;

    if(currentindex.row()==-1)
    {
        QMessageBox::warning(this,"注意","未选定有效数据 !");
        return;
    }
    QStandardItem *currentItem = mdRelated->itemFromIndex(currentindex);

    int parentRow = currentindex.parent().row();

    if(!currentItem->parent())
    {
        //当前选择操作的是父节点
        QMessageBox:: StandardButton result = QMessageBox::warning(NULL, "注意", "是否删除整组数据？",QMessageBox::Yes|QMessageBox::No);
        if(result != QMessageBox::Yes){
            return;
        }

        QString name = currentindex.data().toString();
        sq = "delete from reci_ck_diag_drug where  dept_code = '" + dept_constrain + "' and ";
        if(ui->rbD2I->isChecked())
        {
            sq += " diag_name = '" + name + "'";
        }else{
            sq += " item_name = '" + name + "'";
        }
        qrm->exec(sq);
        mdRelated->removeRow(currentindex.row());

    }
    else
    {
        //子节点
        QString nameParent = currentindex.parent().data().toString();
        QString nameChild = currentindex.data().toString();
        sq = "delete from reci_ck_diag_drug where  dept_code = '" + dept_constrain + "' and ";
        if(ui->rbD2I->isChecked())
        {
            sq += " diag_name = '" + nameParent + "' and item_name = '" + nameChild + "'";
        }else{
            sq += " diag_name = '" + nameChild + "' and item_name = '" + nameParent + "'";
        }
        qrm->exec(sq);

        QStandardItem *parent = currentItem->parent();
        parent->removeRow(currentindex.row());
        if(parent->rowCount()<1)
        {
            //删除之后，父节点再无其它子节点，父节点同时删除
            mdRelated->removeRow(parentRow);
        }
    }
}


void Form_ys_env::on_rbD2I_clicked()
{
    on_pbSearchRelated_clicked();
}

void Form_ys_env::on_rbI2D_clicked()
{
    on_pbSearchRelated_clicked();
}

void Form_ys_env::on_rbCompared_clicked()
{
    on_pbSearchS_clicked();
}

void Form_ys_env::on_rbAll_clicked()
{
    on_pbSearchS_clicked();
}

void Form_ys_env::on_pbFreshGroup_clicked()
{

    mdGroup->clear();
    sq = "select folder_name,folder_id from met_com_groupfolder where dept_code = '"+dept_constrain+"'"
         " and group_type = '1' and group_kind = '2'  order by folder_ord ";// order by ext_code
    qro->exec(sq);
    qDebug()<<"select folders : " << sq;
    QList<QStandardItem *> itemListRow, itemListColumn;//, itemListFN, itemlistFI;
    QStandardItem  *it, *base;//*itemParent, *itemChild,

    while(qro->next())
    {
        QString fdnm = qro->value(0).toString();
        QString fdid = qro->value(1).toString();

        it = new QStandardItem(fdnm);
        mdGroup->appendRow(it);
        it = new QStandardItem(fdid);
        itemListColumn << it;
    }
    mdGroup->appendColumn(itemListColumn);

    for(int i = 0; i< mdGroup->rowCount(); i++)
    {
        base = mdGroup->item(i,0);
        it = mdGroup->item(i,1);
        sq = "select groupname,groupid from MET_COM_GROUP t where "
             " folder_id = '" + it->text() + "' order by group_ord";
        qrot->exec(sq);
        itemListRow.clear();
        itemListColumn.clear();
        while (qrot->next())
        {
            QString grnm = qrot->value(0).toString();
            QString grid = qrot->value(1).toString();
            it = new QStandardItem(grnm);
            itemListRow << it;
            it = new QStandardItem(grid);
            itemListColumn << it;

        }
        base->appendRows(itemListRow);
        base->appendColumn(itemListColumn);
    }

    mdGroup->setHeaderData(0, Qt::Horizontal, "常用组套");
    ui->tvGroup->setModel(mdGroup);
    ui->tvGroup->setColumnHidden(1,true);

    //ui->grpGroup->setVisible(false);
    ui->grpFolder->setVisible(false);
}

void Form_ys_env::on_tvGroup_clicked(const QModelIndex &index)
{
    QStandardItem *currentItem = mdGroup->itemFromIndex(index);

    ui->cbbRange->setCurrentIndex(-1);

    if(currentItem->parent())
    {
        sq = "delete from tmp_group_detail";
        qrm->exec(sq);
        groupId = index.siblingAtColumn(1).data().toString();
        folderId = currentItem->parent()->index().siblingAtColumn(1).data().toString();

        sq = "select item_name, item_code ,qty ,qty_unit , "
             " usage_code ,frequency_code , once_dose, dose_unit,"
             " seqid, item_type, exe_deptcode, ext_code "
             " from met_com_groupdetail ";// = '";dept_constrain + exe_deptcode"'
        sq += " where groupid = '" + groupId + "' order by seqid  ";

        qro->exec(sq);
        qDebug()<<"查询指定组合名称的内容："<<sq;

        while(qro->next())
        {
            sq = "insert into tmp_group_detail "
                 "(item_name, item_code, frequency, usages , once_dose , "
                 "dose_unit,qty, qty_unit,seq,item_type,exe_deptcode, ext_code)";
            sq += " values('" + qro->value("item_name").toString() + "','";
            sq += qro->value("item_code").toString() + "','";
            sq += pub::getDicN("频次", qro->value("frequency_code").toString()) + "','";
            sq += pub::getDicN("给药途径", qro->value("usage_code").toString()) + "',";
            sq += QString::number(qro->value("once_dose").toDouble(),'f',3) + ",'";
            sq += qro->value("dose_unit").toString() + "',";
            sq += QString::number(qro->value("qty").toInt()) + ",'";
            sq += qro->value("qty_unit").toString() + "', ";
            sq += qro->value("seqid").toString() +",'";
            sq += qro->value("item_type").toString() + "','";
            sq += qro->value("exe_deptcode").toString() + "','";
            sq += qro->value("ext_code").toString() + "')";
            qrm->exec(sq);
            qDebug()<<"组合内容写入 tmp group detail ："<<sq;
            item_seq = qro->value("seqid").toInt();
        }

        sq = "select item_name 项目名称, qty 数量,qty_unit 单位, usages 用法,"//0-3
             " frequency 频次, concat(once_dose , dose_unit) 用量,"//4-5
             " once_dose, dose_unit, item_code, ext_code, "//6-9
             " case when item_type ='1' then '药品' else ("
             " case when item_type ='2' then '耗材' else '诊疗' end ) end 类别, "//10
             " item_type, exe_deptcode"//11-12
             " from tmp_group_detail  order by seq  ";
        qDebug()<<"在编辑区显示组合内容："<<sq;
        mdGroupDetail->setQuery(sq, pub::db_m);
        //tvGroupDetailRefresh();

        ui->cbbGroupName->setCurrentText(currentItem->parent()->text());
        ui->leComboName->setText(currentItem->text());
        //ui->grpGroup->setVisible(true);
        ui->grpFolder->setVisible(false);
        sq = "select group_ord, remark from met_com_group where groupid = '" + groupId + "'";
        qro->exec(sq);
        qro->next();
        ui->leComboOrd->setText(qro->value(0).toString());
        if(qro->value(1).toString() == "1")
        {
            ui->ckbStop->setChecked(true);
        }else
        {
            ui->ckbStop->setChecked(false);
        }

    }else{
        mdGroupDetail->setQuery("");
        ui->tvGroupDetail->setModel(mdGroupDetail);
        groupId = "";
        folderId = index.siblingAtColumn(1).data().toString();
        ui->cbbGroupName->setCurrentText(currentItem->text());
        ui->leComboName->setText("");
        //ui->grpGroup->setVisible(false);
        ui->grpFolder->setVisible(true);

        sq = "select folder_ord from met_com_groupfolder where folder_id = '" + folderId + "'";
        qro->exec(sq);
        qDebug()<<"display current folder order : " << sq;
        qro->next();
        ui->leFolderOrd->setText(qro->value(0).toString());
    }

    tvGroupDetailRefresh();

}

void Form_ys_env::on_tvGroupDetail_doubleClicked(const QModelIndex &index)
{
    on_tvGroupDetail_clicked(index);
}

void Form_ys_env::on_tvGroupDetail_clicked(const QModelIndex &index)
{

    sq = "select specs from pha_com_baseinfo "
         " where drug_code = '"+index.siblingAtColumn(8).data().toString()+"'";
    qro->exec(sq);
    qro->next();
    ui->leSpecs->setText(qro->value(0).toString());

    ui->leItemName->setText(index.siblingAtColumn(0).data().toString());
    ui->leCnt->setText(index.siblingAtColumn(1).data().toString());
    ui->leUseCnt->setText(index.siblingAtColumn(6).data().toString());
    ui->cbbPackUnit->setCurrentText(index.siblingAtColumn(2).data().toString());
    ui->cbbUsage->setCurrentText(index.siblingAtColumn(3).data().toString());
    ui->cbbFreq->setCurrentText(index.siblingAtColumn(4).data().toString());
    //ui->cbbDoseUnit->setCurrentText(index.siblingAtColumn(7).data().toString());
    ui->le_dose_unit->setText(index.siblingAtColumn(7).data().toString());
    ui->cbbRange->setCurrentText(index.siblingAtColumn(10).data().toString());

    if(index.siblingAtColumn(9).data().toString() == "1")
    {
        //当前项目为组合
        current_item_is_group = true;
    }
    else
    {
        current_item_is_group = false;
    }

    ui->pt_drug_describe->clear();

    sq = "select dept_name from com_department where dept_code = '"
            + index.siblingAtColumn(12).data().toString() + "'";
    qrmt->exec(sq);
    qrmt->next();
    QString dpnm = qrmt->value(0).toString();
    qDebug() <<"查询项目执行科室："<< sq;
    qDebug() << "执行科室 : " << dpnm;

    if(ui->cbbExecDept->findText(dpnm) < 0)
    {
        ui->cbbExecDept->setCurrentIndex(-1);
    }else{
        ui->cbbExecDept->setCurrentText(dpnm);
    }

    item_code = index.siblingAtColumn(8).data().toString();

    if(ui->cbbRange->currentText() == "药品")
    {
        sq = "select list_type, med_list_codg from fin_com_compare "
             " where fixmedins_hilist_id = '" + item_code + "'";
        qro->exec(sq);
        if(!qro->next())
        {
            ui->pt_drug_describe->clear();
            QMessageBox::information(this, "注意", "在 fin_com_compare 表中找不到药品信息！");
            return;
        }

        QString tip;
        QString list_type = qro->value(0).toString();
        if(list_type == "101")
        {
            //西药中成药
            sq = "select 注册名称,注册剂型,药品规格,最小包装数量,最小制剂单位,最小包装单位,"
                 " 生产企业名称,批准文号,每次用量,功能主治 "
                 " from new_down_1301 "
                 " where 医疗目录编码 = '" + qro->value(1).toString() + "'";
            qDebug()<<"提取药品项目明细信息："<<sq<<"\n";
            qrm->exec(sq);
            qrm->next();

            tip = "药品名称：" + qrm->value("注册名称").toString() + "/";
            tip += qrm->value("注册剂型").toString() + "     规格包装：";
            tip += qrm->value("药品规格").toString() + " ";
            tip += qrm->value("最小包装数量").toString() ;
            tip += qrm->value("最小制剂单位").toString() + "/";
            tip += qrm->value("最小包装单位").toString() + "\n";

            tip += "生产厂家：" + qrm->value("生产企业名称").toString() + "\n";
            tip += "批准文号：" + qrm->value("批准文号").toString() + "\n";
            tip += "用法用量：" + qrm->value("每次用量").toString() + "\n";
            tip += "功能主治：" + qrm->value("功能主治").toString() + "\n";
        }
        else if(list_type == "103")
        {
            //自制剂
            sq = "select 药品商品名,剂型,药品规格,最小包装数量,最小制剂单位名称,最小包装单位,"
                 "生产企业名称,批准文号,每次用量,功能主治 "
                 " from new_down_1303 "
                 " where 医疗目录编码 = '" + qro->value(1).toString() + "'";
            qDebug()<<"提取药品项目明细信息："<<sq<<"\n";
            qrm->exec(sq);
            qrm->next();

            tip = "药品名称：" + qrm->value("药品商品名").toString() + "/";
            tip += qrm->value("剂型").toString() + "     规格包装：";
            tip += qrm->value("药品规格").toString() + " ";
            tip += qrm->value("最小包装数量").toString() ;
            tip += qrm->value("最小制剂单位名称").toString() + "/";
            tip += qrm->value("最小包装单位").toString() + "\n";

            tip += "生产厂家：" + qrm->value("生产企业名称").toString() + "\n";
            tip += "批准文号：" + qrm->value("批准文号").toString() + "\n";
            tip += "用法用量：" + qrm->value("每次用量").toString() + "\n";
            tip += "功能主治：" + qrm->value("功能主治").toString() + "\n";
        }
        else
        {
            ui->pt_drug_describe->clear();
            qDebug()<<"fin_com_compare 表中 list_type : "<<list_type<<"\n";
        }


        ui->pt_drug_describe->setPlainText(tip);

    }
    else
    {
        ui->pt_drug_describe->clear();
    }

}

void Form_ys_env::on_leSearchG_returnPressed()
{
    item_code = "";
    current_item_is_group = false;

    if(ui->cbbRange->currentText() == "药品")
    {
        //sq = "select trade_name, specs, drug_code from pha_com_baseinfo where valid_state = '1' and ( spell_code like ";
        //sq += "'%"+ui->leSearchG->text().trimmed().toUpper();
        //sq += "%' or trade_name like '%"+ui->leSearchG->text().trimmed()+"%')";

        sq = "select BASE.trade_name 药品名称, BASE.specs 规格, "
             "BASE.drug_code 药品编码, "
             " COMP.FAC_NAME 生产厂家, base.dose_unit "
             " from pha_com_baseinfo base"
             " LEFT JOIN PHA_COM_COMPANY comp "
             "       on COMP.FAC_CODE = BASE.PRODUCER_CODE"
             " where BASE.valid_state = '1' "
             " and ( BASE.spell_code like '%" + ui->leSearchG->text().trimmed().toUpper() + "%'"
             " or BASE.trade_name like '%" + ui->leSearchG->text().trimmed() + "%')" ;

    }
    else if(ui->cbbRange->currentText() == "耗材")
    {
        sq = "select item_name, 'specs', item_code, unitflag "
             " from fin_com_undruginfo where valid_state = '1' and "
             " fee_code = '010' and ( spell_code like ";
        sq += "'%"+ui->leSearchG->text().trimmed().toUpper();
        sq += "%' or item_name like '%"+ui->leSearchG->text().trimmed()+"%')";
    }
    else if(ui->cbbRange->currentText() == "诊疗")
    {
        sq = "select item_name, 'specs', item_code, unitflag "
             " from fin_com_undruginfo where valid_state = '1' and "
             " fee_code <> '010' and ( spell_code like ";
        sq += "'%"+ui->leSearchG->text().trimmed().toUpper();
        sq += "%' or item_name like '%"+ui->leSearchG->text().trimmed()+"%')";
    }
    else
    {
        QMessageBox::information(this, "注意", "范围选择无效！");
        return;
    }
qDebug()<<sq;

    mdPop->setQuery( sq , pub::db_o);

    if(mdPop->rowCount() == 0)
    {
        QMessageBox::information(this, "注意", "指定关键字找不到有效的项目！");
        return;
    }
    else if(mdPop->rowCount() == 1)
    {
        item_code = mdPop->record(0).value(2).toString();
        ui->leItemName->setText(mdPop->record(0).value(0).toString());
        ui->leSpecs->setText( mdPop->record(0).value(1).toString());
        ui->le_dose_unit->setText( mdPop->record(0).value(4).toString());
        if(ui->cbbRange->currentText() != "药品")
        {
            if(mdPop->record(0).value(3).toString() == "1")
            {
                current_item_is_group = true;
            }
        }
    }
    else
    {
        if(ui->cbbRange->currentText() == "药品")
        {
            dlgp->setDisplay(*mdPop,QRect(300, 200, 600, 500),"","0.35^0.25^0^0.3^0");//用 宽度比例为0 实现列隐藏
        }
        else
        {
            dlgp->setDisplay(*mdPop,QRect(300, 200, 600, 500),"","0.4^0.3^0^0");//用 宽度比例为0 实现列隐藏
        }
        popRetStr = "";
        dlgp->setModal(true);
        dlgp->exec();

        popRetStr = dlgp->retStr();
        if(popRetStr.isEmpty())
        {
            return;
        }
        item_code = pub::getStr(popRetStr, "^", 3);
        ui->leItemName->setText(pub::getStr(popRetStr, "^", 1));
        ui->leSpecs->setText( pub::getStr(popRetStr, "^", 2));
        ui->le_dose_unit->setText( pub::getStr(popRetStr, "^", 5));

        if(ui->cbbRange->currentText() != "药品")
        {
            if(pub::getStr(popRetStr, "^", 4) == "1")
            {
                current_item_is_group = true;
            }
        }
    }

    //sq = "select item_name"
}

void Form_ys_env::on_pbSaveG_clicked()
{
    QString fName, gName;   //foldername, groupname
    fName = ui->cbbGroupName->currentText().trimmed();
    gName = ui->leComboName->text().trimmed();
    if( fName.isEmpty() || gName.isEmpty())
    {
        QMessageBox::information(this, "注意", "组名称和组套名称不可以空！");
        return;
    }

    if(mdGroupDetail->rowCount() < 1)
    {
        QMessageBox::information(this, "注意", "组套明细不可以为空！");
        return;
    }

    //组套排序
    int ord = ui->leComboOrd->text().toUInt();
    if(ord < 1)
    {
        QMessageBox::warning(this, "注意", "为组套指定的序号无效！");
        return;
    }

    //组套目录是否存在
    sq = "select folder_id from met_com_groupfolder where folder_name = "
         "'" + fName + "' and dept_code = '" + dept_constrain + "' ";
    qro->exec(sq);
qDebug()<<sq;
    if(qro->next())
    {
        folderId = qro->value(0).toString();
    }
    else
    {
        qro->exec("select SEQ_MET_GROUPFOLDERID.nextval from dual");
        qro->next();
        folderId = qro->value(0).toString();
        sq = "insert into met_com_groupfolder ( folder_id,folder_name,group_type,group_kind,dept_code,"
             "doct_code, oper_code,oper_date,parent_id,share_flag) ";
        sq += "values('" + folderId + "','" + fName + "','1','2','"+dept_constrain + "','"+pub::usr_code;
        sq += "','"+pub::usr_code+"',sysdate,'ROOT','0')";
        qro->exec(sq);
qDebug()<<sq;
    }

    //组套名称是否存在
    sq = "select groupname from met_com_group where dept_code = '" + dept_constrain + "' and groupname = '" + gName + "'";
    qro->exec(sq);
    qDebug()<<"组套名称是否存在 : "<<sq;

    QString stat = "";
    if(ui->ckbStop->isChecked())
    {
        stat = "1";
    }else{
        stat = "0";
    }
    if(qro->next()){
        QMessageBox:: StandardButton result = QMessageBox::warning(NULL, "注意", "组套名称已经存在，是否覆盖？",QMessageBox::Yes|QMessageBox::No);
        if(result != QMessageBox::Yes){
            return;
        }
        //删除旧数据
        sq = "delete from met_com_groupdetail where groupid = '" + groupId + "'";
        qro->exec(sq);

        //变更组套属性
        sq = "update met_com_group set folder_id = '"+folderId+"' , group_ord = '" + QString::number(ord) + "' ,";
        sq += " remark = '" + stat + "'";
        sq += " where groupid = '"+groupId+"'";
        qro->exec(sq);
        qDebug()<<"变更组套属性 : "<<sq;
    }
    else    //新组套
    {
        qro->exec("select SEQ_MET_GROUP_ID.nextval from dual");
        qro->next();
        groupId = qro->value(0).toString();
        sq = "insert into met_com_group ";
        sq += "(groupid,groupname,group_type,group_kind,oper_code,oper_date,folder_id,share_flag ,dept_code,group_ord,remark) ";
        sq += " values('"+groupId+"','"+gName+"','1','2','"+pub::usr_code+"',sysdate,'"+folderId;
        sq += "','0','" + dept_constrain + "'," + QString::number(ord) + ",";
        sq += "'" + stat + "')";
        qro->exec(sq);
        qDebug()<<"新建组套 ： "<<sq;
    }

    qro->exec("select SEQ_MET_ORDER_COMBONO.nextval from dual");
    qro->next();
    QString comb_no = qro->value(0).toString();

    sq = "select item_name , qty ,qty_unit , usages ,frequency , "
         " once_dose, dose_unit, item_code, "
         " seq, item_type, exe_deptcode, ext_code "
         " from tmp_group_detail ";

    qrm->exec(sq);
    while(qrm->next())
    {

        sq = "insert into met_com_groupdetail"
             "(groupid,seqid,item_code,item_name,type_code,frequency_code,usage_code,"
             "once_dose,dose_unit,qty,qty_unit,days,"
             "comb_no,main_drug,oper_code,oper_date,item_type,exe_deptcode,ext_code)";
        sq += " values (" ;
        sq += "'" + groupId + "',";
        sq += "'" + qrm->value("seq").toString()+"',";
        sq += "'" + qrm->value("item_code").toString()+"'," ;
        sq += "'" + qrm->value("item_name").toString().trimmed() + "',";
        sq += "'MZ',";
        sq += "'" + pub::getDicC("频次",qrm->value("frequency").toString()) + "'," ;
        sq += "'" + pub::getDicC("给药途径",qrm->value("usages").toString()) + "',";
        sq += qrm->value("once_dose").toString() + ",";
        sq += "'" + qrm->value("dose_unit").toString() + "',";
        sq += qrm->value("qty").toString() + ",";
        sq += "'" + qrm->value("qty_unit").toString() + "',";
        sq += "'1',";
        sq += "'" + comb_no + "',";
        sq += "'0',";
        sq += "'" + pub::usr_code + "', ";
        sq += " sysdate,";
        sq += "'" + qrm->value("item_type").toString()+"',";
        sq += "'" + qrm->value("exe_deptcode").toString()+"',";
        sq += "'" + qrm->value("ext_code").toString()+"'";
        sq += ")";
        qro->exec(sq);
        qDebug()<<"插入组套明细项目 ,"<<qrm->value("item_name").toString()<<" : "<<sq;
    }

    QMessageBox::information(this, "注意", "组套数据保存完成！");

    on_pbFreshGroup_clicked();
    mdGroupDetail->setQuery("");

}

void Form_ys_env::on_pbAddItem_clicked()
{
    if(ui->leCnt->text().toInt() < 1 )
    {
        QMessageBox::information(this, "注意", "数量不正确！");
        return;
    }

    if(ui->cbbPackUnit->currentIndex() == -1 )
    {
        QMessageBox::information(this, "注意", "项目单位不允许空！");
        return;

    }

    if(ui->leItemName->text().isEmpty())
    {
        QMessageBox::information(this, "注意", "项目名称不允许空！");
        return;
    }

    if(ui->cbbRange->currentText() == "药品") //
    {
        double onceDose = ui->leUseCnt->text().toDouble();
        if( qFuzzyCompare( onceDose ,0) || onceDose < 0)
        {
            QMessageBox::information(this, "注意", "药品单次用量无效！");
            return;
        }

        if(ui->cbbUsage->currentIndex() == -1
                || ui->cbbFreq->currentIndex() == -1
        //       || ui->cbbDoseUnit->currentIndex() == -1
                )
        {
            QMessageBox::information(this, "注意", "药品项目所有信息都必须完整！");
            return;
        }

    }

    if(ui->cbbRange->currentText() == "诊疗") //
    {
        if(ui->cbbFreq->currentIndex() == -1 )
        {
            QMessageBox::information(this, "注意", "诊疗项目频次不可以为空！");
            return;
        }

    }

    if(ui->cbbRange->currentText() != "耗材" && !current_item_is_group) //
    {
        //耗材无 icpc 编码, 组合项目不需要查询icpc码
        sq = " select item_code from com_dict_icpc where item_code = '" + item_code + "'";
        qrm->exec(sq);
        if(!qrm->next())
        {
            QMessageBox::information(this, "注意", "请先在icpc字典库添加项目 " + ui->leItemName->text() + " ！");
            return;
        }
    }


    item_seq++;

    sq = "replace into tmp_group_detail (item_name, item_code, frequency, usages ,"
         " once_dose , dose_unit,qty, qty_unit,seq,item_type,exe_deptcode, ext_code)";
    sq += " values('";
    sq += ui->leItemName->text() + "','";
    sq += item_code + "','";
    sq += ui->cbbFreq->currentText() + "','";
    sq += ui->cbbUsage->currentText() + "',";
    sq += (ui->leUseCnt->text().isEmpty() ? "0" : ui->leUseCnt->text()) + ",'";
    //sq += ui->cbbDoseUnit->currentText() + "',";
    sq += ui->le_dose_unit->text() + "',";
    sq += ui->leCnt->text() + ",'";
    sq += ui->cbbPackUnit->currentText() + "',";
    sq += QString::number( item_seq ) +",'";
    QString t;
    if(ui->cbbRange->currentText() == "药品")
    {
        t = "1";
    }
    else if(ui->cbbRange->currentText() == "耗材")
    {
        t = "2";
    }
    else if(ui->cbbRange->currentText() == "诊疗")
    {
        t = "3";
    }
    else
    {
        QMessageBox::information(this, "注意", "项目范围错误！");
        return;
    }

    qrm->exec("select dept_code from com_department where dept_name = '"+ui->cbbExecDept->currentText()+"'");
    if(!qrm->next())
    {
        QMessageBox::information(this, "注意", "保存错误，执行科室不可以为空！");
        return;
    }

    sq += t +"','"+qrm->value(0).toString()+"',";

    if(current_item_is_group)
    {
        //组合项目
        sq += "'1'";
    }
    else
    {
        //独立项目
        sq += "'0'";
    }

    sq += ")";

    if(!qrm->exec(sq)){
        QMessageBox::information(this, "注意", "保存错误，请确认数据项目完整且有效！");
        qDebug()<<"sql is : "<<sq;
        return;
    }

    sq = "select item_name 项目名称, qty 数量,qty_unit 单位, "
         " usages 用法,frequency 频次, concat(once_dose , dose_unit) 用量,"
         " once_dose, dose_unit, item_code, ext_code, "
         " case when item_type ='1' then '药品' else ("
         " case when item_type ='2' then '耗材' else '诊疗' end ) end 类别 , item_type"
         " from tmp_group_detail  order by seq  ";

    mdGroupDetail->setQuery(sq, pub::db_m);
    tvGroupDetailRefresh();
}

void Form_ys_env::on_pbRemoveItem_clicked()
{
    if(!ui->tvGroupDetail->currentIndex().isValid()){
        QMessageBox::information(this, "注意", "请指定需要删除的数据行！");
        return;

    }
    QString itcd = ui->tvGroupDetail->currentIndex().siblingAtColumn(8).data().toString();
    sq = "delete from tmp_group_detail where item_code = '" + itcd +"'" ;

    qrm->exec(sq);

    sq = "select item_name 项目名称, qty 数量,qty_unit 单位, usages 用法,frequency 频次, concat(once_dose , dose_unit) 用量,"
         " once_dose, dose_unit, item_code, ext_code, "
         " case when item_type ='1' then '药品' else ("
         " case when item_type ='2' then '耗材' else '诊疗' end ) end 类别 , item_type"
         " from tmp_group_detail  order by seq  ";

    mdGroupDetail->setQuery(sq, pub::db_m);
    tvGroupDetailRefresh();
}

void Form_ys_env::tvGroupDetailRefresh()
{

    ui->leSpecs->clear();
    ui->leItemName->clear();
    ui->leCnt->clear();
    ui->leUseCnt->clear();
    ui->cbbPackUnit->setCurrentIndex(-1);
    ui->cbbUsage->setCurrentIndex(-1);
    ui->cbbFreq->setCurrentIndex(-1);
    ui->le_dose_unit->clear();
    ui->cbbExecDept->setCurrentIndex(-1);
    ui->pt_drug_describe->clear();

    int w = ui->tvGroupDetail->width();
    ui->tvGroupDetail->setModel(mdGroupDetail);

    pub::setColumnWidth(ui->tvGroupDetail, "0.3^0.2^0.1^0.1^0.1^0.1^0^0^0^0^0.05^0^0", w, 15);

}

void Form_ys_env::on_pbRemoveG_clicked()
{
    QMessageBox:: StandardButton result = QMessageBox::warning(NULL, "注意", "确定要删除指定的组套名称？",QMessageBox::Yes|QMessageBox::No);
    if(result != QMessageBox::Yes){
        return;
    }
    sq = "delete from met_com_groupdetail where groupid = '" + groupId + "'";
    qro->exec(sq);
    sq = "delete from met_com_group where groupid = '" + groupId + "'";
    qro->exec(sq);
    //QMessageBox::warning(NULL, "注意", "确定要删除指定的组套名称？",QMessageBox::Yes|QMessageBox::No);
    on_pbFreshGroup_clicked();
    mdGroupDetail->setQuery("");
}

void Form_ys_env::on_pbSaveFolderOrd_clicked()
{
    int ord = ui->leFolderOrd->text().toUInt();
    if(ord < 1)
    {
        QMessageBox::warning(this, "注意", "为组指定的序号无效！");
        return;
    }

    sq = "update met_com_groupfolder set folder_ord = " + QString::number(ord) + " where folder_id = '"+folderId+"'";
    qDebug()<<"change folder order : " << sq;
    qDebug()<<"folder id is : " << folderId;
    if(qro->exec(sq))
    {
        QMessageBox::information(this, "注意", "组序号已保存，下次进入系统生效！");
    }else{
        QMessageBox::information(this, "注意", "组序号已保存失败！\n" + qro->lastError().text());
        qDebug()<<sq;
    }
}

void Form_ys_env::on_leKeyS_returnPressed()
{
    on_pbSearchS_clicked();
}

void Form_ys_env::on_leKeyD_returnPressed()
{
    on_pbSearchD_clicked();
}

void Form_ys_env::on_leKeyDiag_returnPressed()
{
    on_pbSearchDiag_clicked();
}

void Form_ys_env::on_leKeyItem_returnPressed()
{
    on_pbSearchItem_clicked();
}

void Form_ys_env::on_leKeyRelated_returnPressed()
{
    on_pbSearchRelated_clicked();
}

void Form_ys_env::on_rbDoct_clicked()
{
    on_pbFresh_clicked();
}

void Form_ys_env::on_rbCom_clicked()
{
    on_pbFresh_clicked();
}

void Form_ys_env::on_toolButton_clicked()
{    
    if(!ui->tvDest->currentIndex().isValid())
    {
        QMessageBox::information(this, "注意", "未选定行！");
        return;
    }

    sq = "update com_dict_icpc set  ";
    sq += " py = '" + ui->leSpell_2->text().trimmed().toUpper() + "'";
    sq += " where atinc = " +  ui->tvDest->currentIndex().siblingAtColumn(6).data().toString();
    qDebug()<<sq;
    if(qrm->exec(sq))
    {
        QMessageBox::information(this, "注意", "更新成功，重新检索之后可看到变更结果！");
    }else
    {
        QMessageBox::information(this, "注意", "数据更新失败！\n" + qrm->lastError().text() + "\n" + sq);
    }
}

void Form_ys_env::threadMsg(QString s)
{

    if(s == "finish"){
        dlgp1->setNeedClose(true);
        dlgp1->closeWindow();
    }
    else if(s.left(3) == "msg")
    {
        dlgp1->setText(sqlMsg[pub::getStr(s, "^", 2).toInt()]);
    }
    else if(s.left(8) == "rollback")
    {
        dlgp1->setText("线程 SQL 发生错误，正在回滚。。。");
    }
    else if(s.left(3) == "err"){
        dlgp1->setNeedClose(true);
        dlgp1->closeWindow();
        qDebug()<<" SQL thread " +s;
        QMessageBox::warning(this, "注意", "线程中的sql执行发生错误！\n" + s);
    }
    else
    {
        qDebug()<<" SQL thread return invalid message : " +s;
    }
}

void Form_ys_env::on_tvSourceIcd_clicked(const QModelIndex &index)
{
    if(ui->ckb_no_icpc->isChecked())  // || IcpcDicType == "2"  诊断结论  IcpcDicType == "0" 就诊原因
    {
        //不需要查找
        return;
    }

    QModelIndex idx;
    QString code = index.siblingAtColumn(0).data().toString();
    QString value = index.siblingAtColumn(1).data().toString();

    int rows = mdSourceIcpc->rowCount();

    bool found = false;

    for(int i = 0; i< rows; i++)
    {
        idx = mdSourceIcpc->index(i, 0);

        if(IcpcDicType == "2") //  西医诊断结论
        {
            if(idx.siblingAtColumn(1).data().toString() == value)
            {
                found = true;
                break;
            }
        }
        else
        {

            if(idx.siblingAtColumn(2).data().toString() == code
                    ||idx.siblingAtColumn(3).data().toString() == code
                    ||idx.siblingAtColumn(4).data().toString() == code)
            {
                found = true;
                break;
            }
        }
    }

    if(found)
    {
        ui->tvSourceIcpc->setCurrentIndex(idx);
        on_tvSourceIcpc_clicked(idx);
    }else{
        QMessageBox::warning(this, "注意", "icpc目录中未找到匹配记录！");
    }

}

void Form_ys_env::on_tvSourceIcd_doubleClicked(const QModelIndex &index)
{
    on_tvSourceIcd_clicked(index);
}

void Form_ys_env::on_tvSourceIcpc_clicked(const QModelIndex &index)
{
    QString itm_nm = index.siblingAtColumn(1).data().toString();
    ui->leSpell->setText(pub::getFirstLetters(itm_nm));
}

void Form_ys_env::on_tvDest_clicked(const QModelIndex &index)
{

    ui->leSpell_2->setText(index.siblingAtColumn(7).data().toString());
}

void Form_ys_env::on_tvDest_doubleClicked(const QModelIndex &index)
{
    ui->leSpell_2->setText(index.siblingAtColumn(7).data().toString());
    QString icd_code = index.siblingAtColumn(1).data().toString();

    if(ui->rb04->isChecked())
    {
        //药品
        sq = " select 注册名称,注册剂型,药品规格,最小包装数量,最小制剂单位,最小包装单位,"
             " 生产企业名称,批准文号,每次用量,功能主治 "
             " from new_down_1301 "
             " where 医疗目录编码 = '" + icd_code + "'";
        qDebug()<<"提取药品项目明细信息："<<sq<<"\n";
        qrm->exec(sq);
        if(!qrm->next())
        {
            QMessageBox::information(this, "注意", "药品项目信息不存在，请检查此项目是否已经停用！");
            return;
        }

        QString tip = qrm->value("注册名称").toString() + "/";
        tip += qrm->value("注册剂型").toString() + "\n";

        tip += qrm->value("药品规格").toString() + " ";
        tip += qrm->value("最小包装数量").toString() ;
        tip += qrm->value("最小制剂单位").toString() + "/";
        tip += qrm->value("最小包装单位").toString() + "\n";

        tip += qrm->value("生产企业名称").toString() + "\n";
        tip += qrm->value("批准文号").toString() + "\n";
        tip += qrm->value("每次用量").toString() + "\n";
        tip += qrm->value("功能主治").toString() + "\n";

        QMessageBox::information(this, "药品信息", tip);
    }


}

void Form_ys_env::on_cbbKey_currentTextChanged(const QString &arg1)
{
    ui->leKey->setText(arg1);
}

void Form_ys_env::on_pbCreateFolder_clicked()
{
    QString folder_id, fName;   //foldername, groupname
    fName = ui->cbbGroupName->currentText().trimmed();
    if( fName.isEmpty() )
    {
        QMessageBox::information(this, "注意", "组名称不可以空！");
        return;
    }
    //组套目录是否存在
    sq = "select folder_id from met_com_groupfolder where folder_name = "
         "'" + fName + "' and dept_code = '" + dept_constrain + "' ";
    qro->exec(sq);
    qDebug()<<"检查组名称是否存在 : "<<sq;
    if(!qro->next())
    {
        QMessageBox::information(this, "注意", "组名称不存在！");
        return;
    }

    folder_id = qro->value(0).toString();

    //组套目录是否空?
    sq = "select folder_id from met_com_group where folder_id = '" + folder_id + "'";
    qro->exec(sq);
    qDebug()<<"组套目录是否空 : "<<sq;
    if(qro->next() )
    {
        QMessageBox::information(this, "注意", "组名称非空，无法删除！");
        return;
    }
    //组删除
    sq = "delete from met_com_groupfolder where folder_id = '" + folder_id + "'";
    qro->exec(sq);
    qDebug()<<"组删除 : "<<sq;
    QMessageBox::information(this, "注意", "指定名称的组已删除！");
}

void Form_ys_env::on_pbSearchRelated_2_clicked()
{
    sq = "select name,code from com_dictionary where  type ='DOSAGEFORM' and valid_state = '1' order by sort_id";
    qDebug()<<"提取药品剂型："<<sq;

    md_form->setQuery(sq, pub::db_o);
    ui->tv_doseform->setModel(md_form);
    int width = ui->tv_doseform->width();
    pub::setColumnWidth(ui->tv_doseform, "0.85", width, 10);

    sq = "select name,code from com_dict_com where dic_type='给药途径' and valid_flag = '1' ";
    qDebug()<<"提取药品用法："<<sq;

    md_usage->setQuery(sq, pub::db_m);
    ui->tv_usage->setModel(md_usage);
    width = ui->tv_usage->width();
    pub::setColumnWidth(ui->tv_usage, "0.85", width, 10);


    //提取已关联信息
    QStringList title;
    md_form_usage->clear();

    if(ui->rbD2I_2->isChecked())
    {
        title << "药品剂型->给药途径";
        sq = "select  doseform_name 药品剂型, usage_name 给药途径 from reci_ck_doseform_usage  ";
        sq += " order by convert(doseform_name using gbk) ";

    }else{
        title << "给药途径->药品剂型";
        sq = "select usage_name 给药途径, doseform_name 药品剂型 from reci_ck_doseform_usage  ";
        sq += " order by convert(usage_name using gbk) ";

    }

    QStandardItem *item, *it;
    QList<QStandardItem *> itemList;
    qrm->exec(sq);
    QString prev,cur;
    QStringList val;
    qrm->next();
    prev = qrm->value(0).toString();
    it = new QStandardItem( qrm->value(1).toString());
    itemList << it;

    while (true)
    {
        if(!qrm->next())
        {
            item = new QStandardItem(prev);
            item->appendRows(itemList);
            md_form_usage->appendRow(item);
            //item->clearData();
            break;
        }
        cur = qrm->value(0).toString();

        if( prev != cur)
        {
            item = new QStandardItem(prev);
            item->appendRows(itemList);
            itemList.clear();
            md_form_usage->appendRow(item);
            //item->clearData();
            prev = cur;

        }
        it = new QStandardItem( qrm->value(1).toString());
        itemList << it;
    }

    md_form_usage->setHorizontalHeaderLabels(title);
    ui->tv_dosefom_usage->setModel(md_form_usage);


}

void Form_ys_env::on_tbAdd_3_clicked()
{
    if(!ui->tv_doseform->currentIndex().isValid()
            || !ui->tv_usage->currentIndex().isValid())
    {
        QMessageBox::information(this, "注意", "未选定有效数据行！");
        return;
    }
    saveFormUsage();
}

void Form_ys_env::on_tv_doseform_doubleClicked(const QModelIndex &index)
{
    Q_UNUSED(index)

    if(!ui->tv_doseform->currentIndex().isValid()
            || !ui->tv_usage->currentIndex().isValid())
    {
        QMessageBox::information(this, "注意", "未选定有效数据行！");
        return;
    }
    saveFormUsage();
}

void Form_ys_env::on_tv_usage_doubleClicked(const QModelIndex &index)
{
    Q_UNUSED(index)

    if(!ui->tv_doseform->currentIndex().isValid()
            || !ui->tv_usage->currentIndex().isValid())
    {
        QMessageBox::information(this, "注意", "未选定有效数据行！");
        return;
    }
    saveFormUsage();
}

void Form_ys_env::saveFormUsage()
{
    //保存关联关系
    sq = "insert into reci_ck_doseform_usage "
         "(doseform_name, doseform_code, usage_name, usage_code, oper_code, oper_time) values (";
    sq += "'" + ui->tv_doseform->currentIndex().siblingAtColumn(0).data(0).toString().trimmed() + "',";
    sq += "'" + ui->tv_doseform->currentIndex().siblingAtColumn(1).data(0).toString().trimmed() + "',";
    sq += "'" + ui->tv_usage->currentIndex().siblingAtColumn(0).data(0).toString().trimmed() + "',";
    sq += "'" + ui->tv_usage->currentIndex().siblingAtColumn(1).data(0).toString().trimmed() + "',";
    sq += "'"+pub::usr_code+"', now())";

    qDebug()<<"保存关联关系，剂型与用法："<<sq;
    if(!qrm->exec(sq))
    {
        QMessageBox::information(this, "注意", "保存失败！\n" + qrm->lastError().text());
    }
    else
    {
        QString doseform, usage; //剂型，用法
        doseform = ui->tv_doseform->currentIndex().siblingAtColumn(0).data(0).toString().trimmed();
        usage = ui->tv_usage->currentIndex().siblingAtColumn(0).data(0).toString().trimmed();

        //检索父级项目是否已经存在
        QStandardItem * itm ;
        bool found = false;
        for(int i = 0; i< md_form_usage->rowCount(); i++)
        {
            itm = md_form_usage->item(i, 0);
            QString it = itm->text();

            if( it== doseform || it == usage)
            {
                //剂型，用法 不可能相同，不管是诊断关联药品还是药品关联诊断，都按同一逻辑进行判断。
                found = true;
                break;
            }
        }

        QStandardItem *itemparent, *itemChild;

        if(found)
        {
            //存在父级记录，直接添加子记录
            if(ui->rbD2I_2->isChecked())
            {
                //诊断关联药品
                itemChild = new QStandardItem(usage);
                itm->appendRow(itemChild);
            }
            else
            {
                //药品关联诊断
                itemChild = new QStandardItem(doseform);
                itm->appendRow(itemChild);
            }
        }
        else
        {
            //父级记录不存在，新建父级记录，再添加子记录
            if(ui->rbD2I_2->isChecked())
            {
                itemparent = new QStandardItem(doseform);
                itemChild = new QStandardItem(usage);
            }
            else
            {
                itemparent = new QStandardItem(usage);
                itemChild = new QStandardItem(doseform);
            }
            itemparent->appendRow(itemChild);
            md_form_usage->appendRow(itemparent);

        }
    }
}

void Form_ys_env::on_tvItem_clicked(const QModelIndex &index)
{
    ui->le_drug_name_diag->setText(index.siblingAtColumn(0).data().toString());
    sq = "select dose_unit from pha_com_baseinfo where trade_name = '"
            + ui->le_drug_name_diag->text() + "'";
    qrot->exec(sq);
    if(qrot->next())
    {
        ui->le_baseunit->setText(qrot->value(0).toString());
        ui->le_limit_amount->clear();
    }
    else
    {
        QMessageBox::information(this, "注意", " pha_com_baseinfo 中找不到药品名称“"
                                 + ui->le_drug_name_diag->text() + "”！");
    }
}

void Form_ys_env::on_tvDiag_clicked(const QModelIndex &index)
{
    ui->le_diag_name_drug->setText(index.siblingAtColumn(0).data().toString());
    sq = "select gend from reci_ck_diag_gend where diag_name = '" + ui->le_diag_name_drug->text() + "'";
    qrm->exec(sq);

    if(qrm->next())
    {
        if(qrm->value(0).toString() == "女")
        {
            ui->rb_diag_gend_F->setChecked(true);
        }
        else if(qrm->value(0).toString() == "男")
        {
            ui->rb_diag_gend_M->setChecked(true);
        }
        else
        {
            ui->rb_diag_gend_N->setChecked(true);
        }
    }
    else
    {
        ui->rb_diag_gend_N->setChecked(true);
    }
}

void Form_ys_env::on_tvRelated_clicked(const QModelIndex &index)
{

    if(ui->rbD2I->isChecked())
    {
        ui->le_drug_name_diag->setText(index.siblingAtColumn(0).data().toString());
        ui->le_diag_name_drug->setText(index.parent().siblingAtColumn(0).data().toString());
        ui->leKeyItem->setText(index.siblingAtColumn(0).data().toString());
        ui->leKeyDiag->setText(index.parent().siblingAtColumn(0).data().toString());
    }
    else
    {
        ui->le_diag_name_drug->setText(index.siblingAtColumn(0).data().toString());
        ui->le_drug_name_diag->setText(index.parent().siblingAtColumn(0).data().toString());
        ui->leKeyItem->setText(index.parent().siblingAtColumn(0).data().toString());
        ui->leKeyDiag->setText(index.siblingAtColumn(0).data().toString());
    }

    on_pbSearchDiag_clicked();
    on_pbSearchItem_clicked();

    QModelIndex idx;
    bool found = false;

    int rows = mdDiag->rowCount();

    for(int i = 0; i< rows; i++)
    {
        idx = mdDiag->index(i, 0);

        if(idx.siblingAtColumn(0).data().toString() == ui->leKeyDiag->text())
        {
            ui->tvDiag->setCurrentIndex(idx);
            found = true;
            break;
        }
    }

    if(!found)
    {
        ui->le_diag_name_drug->clear();
    }

    rows = mdItem->rowCount();
    found = false;

    for(int i = 0; i< rows; i++)
    {
        idx = mdItem->index(i, 0);

        if(idx.siblingAtColumn(0).data().toString() == ui->leKeyItem->text())
        {
            ui->tvItem->setCurrentIndex(idx);
            found = true;
            break;
        }
    }

    if(!found)
    {
        ui->le_drug_name_diag->clear();
    }

    ui->le_limit_amount->setText(index.siblingAtColumn(1).data().toString());
    if(index.siblingAtColumn(2).data().toString().isEmpty())
    {
        sq = "select dose_unit from pha_com_baseinfo where "
             " trade_name = '" + ui->tvItem->currentIndex().siblingAtColumn(0).data().toString() + "' ";
        qrot->exec(sq);
        qrot->next();
        ui->le_baseunit->setText(qrot->value(0).toString());
    }
    else
    {
        ui->le_baseunit->setText(index.siblingAtColumn(2).data().toString());
    }

}

void Form_ys_env::on_tvRelated_doubleClicked(const QModelIndex &index)
{
    on_tvRelated_clicked(index);
}

void Form_ys_env::on_pbSearchDiag_2_clicked()
{
    sq = "select distinct item_name 项目名称, type from com_dict_icpc " //,icpc_code,nat_code,item_code
         " where valid_flag = '1' and type in('1', '3') and item_name like '%";
    sq += ui->le_key_diag_rule->text().trimmed() + "%' order by convert(item_name using gbk) ";

    md_drug_for_rule_conflict->setQuery(sq, pub::db_m);

    ui->tv_drug_for_rule_conflict->setModel(md_drug_for_rule_conflict);

    int width = ui->tv_drug_for_rule_conflict->width();
    pub::setColumnWidth(ui->tv_drug_for_rule_conflict, "0.85^0", width, 10);
}

void Form_ys_env::on_tb_diag_into_rule_clicked()
{
    if(!ui->tv_drug_for_rule_conflict->currentIndex().isValid())
    {
        QMessageBox::information(this, "注意", "未选定有效数据行！");
        return;
    }

    sq = "replace into tmp_drug_conflict (drug_name, type) values ('"
            + ui->tv_drug_for_rule_conflict->currentIndex().siblingAtColumn(0).data().toString()
            + "','"
            + ui->tv_drug_for_rule_conflict->currentIndex().siblingAtColumn(1).data().toString()
            + "')";
    qrm->exec(sq);

    sq = "select drug_name 药品名称 from tmp_drug_conflict order by convert(drug_name using gbk)";
    md_drug_in_rule_conflict->setQuery(sq, pub::db_m);
    ui->tv_drug_in_rule_conflict->setModel(md_drug_in_rule_conflict);
    ui->tv_drug_in_rule_conflict->setColumnWidth(0, ui->tv_drug_in_rule_conflict->width() * 0.85 );
    ui->tv_drug_in_rule_conflict->setColumnWidth(1, 0 );



}

void Form_ys_env::on_tb_diag_leave_rule_clicked()
{
    if(!ui->tv_drug_in_rule_conflict->currentIndex().isValid())
    {
        QMessageBox::information(this, "注意", "未选定有效数据行！");
        return;
    }

    sq = "delete from tmp_drug_conflict where drug_name = '"
            + ui->tv_drug_in_rule_conflict->currentIndex().siblingAtColumn(0).data().toString() + "'";
    qrm->exec(sq);

    sq = "select drug_name 药品名称 from tmp_drug_conflict order by convert(drug_name using gbk)";
    md_drug_in_rule_conflict->setQuery(sq, pub::db_m);
    ui->tv_drug_in_rule_conflict->setModel(md_drug_in_rule_conflict);
    ui->tv_drug_in_rule_conflict->setColumnWidth(0, ui->tv_drug_in_rule_conflict->width() * 0.85 );


}

void Form_ys_env::on_pb_new_rule_clicked()
{
    if(ui->le_conflict_name->text().trimmed().isEmpty())
    {
        QMessageBox::information(this, "注意", "未指定检验规则名称！");
        ui->le_conflict_name->setFocus();
        return;
    }

    if(md_drug_in_rule_conflict->rowCount() < 2)
    {
        QMessageBox::information(this, "注意", "不合理搭配项目数量至少应为两种！");
        return;
    }

    sq = "select type from tmp_drug_conflict";
    qrm->exec(sq);
    QString last_item_type = "";
    while(qrm->next())
    {
        if(!last_item_type.isEmpty() && last_item_type != qrm->value(0).toString())
        {
            QMessageBox::information(this, "注意", "不允许跨类别定义项目！");
            return;
        }
        last_item_type = qrm->value(0).toString();
    }

    sq = "select conf_name from reci_ck_drug_conflict where conf_name = '" + ui->le_conflict_name->text().trimmed() + "'";
    qrm->exec(sq);
    if(qrm->next())
    {
        QMessageBox::StandardButton bt;
        bt = QMessageBox::question(this, "注意", "指定的冲突规则名称已经存在，是否覆盖？", QMessageBox::Yes | QMessageBox::No);
        if(bt != QMessageBox::Yes)
        {
            return;
        }
        qrm->exec("delete from reci_ck_drug_conflict where conf_name = '" + ui->le_conflict_name->text().trimmed() + "'");
    }
    sq = "select max(conf_id) + 1 from reci_ck_drug_conflict";
    qrm->exec(sq);
    qrm->next();
    QString conf_id = qrm->value(0).toString();
    sq = "select drug_name from tmp_drug_conflict";
    qrm->exec(sq);

    while(qrm->next())
    {
        sq = "insert into reci_ck_drug_conflict (conflict_type,conf_id,conf_name,drug_name,oper_code,oper_time)";
        sq += " values(";
        sq += "'" + ui->cbb_conflict->currentText() + "',";
        sq += conf_id + ",";
        sq += "'" + ui->le_conflict_name->text().trimmed() + "',";
        sq += "'" + qrm->value(0).toString() + "',";
        sq += "'" + pub::usr_code + "',";
        sq += " now() )";
        qDebug()<<"插入用药冲突规则："<<sq;
        if(!qrmt->exec(sq))
        {
            QMessageBox::information(this, "注意", "插入用药冲突规则错误！\n" + qrmt->lastError().text());
            return;
        }
    }

    on_pb_fresh_conflict_rules_clicked();

}

void Form_ys_env::on_pb_fresh_conflict_rules_clicked()
{

    sq = "select distinct conf_name 校验规则名称 from reci_ck_drug_conflict "
         " where conf_name like '%";
    sq += ui->le_key_rule_conflict->text().trimmed() + "%' order by convert(conf_name using gbk) ";


    md_rule_conflict->setQuery(sq, pub::db_m);

    ui->tv_rule_conflict->setModel(md_rule_conflict);

    int width = ui->tv_rule_conflict->width();
    pub::setColumnWidth(ui->tv_rule_conflict, "0.85", width, 10);

    on_pb_clear_conflict_items_clicked();
}

void Form_ys_env::on_tv_rule_conflict_clicked(const QModelIndex &index)
{
    qrm->exec("delete from tmp_drug_conflict");

    ui->le_conflict_name->setText(index.siblingAtColumn(0).data().toString());

    sq = "select drug_name , conflict_type from reci_ck_drug_conflict "
         " where conf_name = '" + ui->le_conflict_name->text() + "'";

    qrm->exec(sq);
    while(qrm->next())
    {
        sq = "insert into tmp_drug_conflict (drug_name) values ('"
                + qrm->value(0).toString() + "')";
        qrmt->exec(sq);
    }

    qrm->previous();
    ui->cbb_conflict->setCurrentText(qrm->value(1).toString());

    sq = "select drug_name 药品名称 from tmp_drug_conflict order by convert(drug_name using gbk)";
    md_drug_in_rule_conflict->setQuery(sq, pub::db_m);
    ui->tv_drug_in_rule_conflict->setModel(md_drug_in_rule_conflict);
    ui->tv_drug_in_rule_conflict->setColumnWidth(0, ui->tv_drug_in_rule_conflict->width() * 0.85 );


}

void Form_ys_env::on_tv_rule_conflict_doubleClicked(const QModelIndex &index)
{
    on_tv_rule_conflict_clicked(index);
}

void Form_ys_env::on_pbSearchDiag_3_clicked()
{
    sq = "select distinct item_name 药品 from com_dict_icpc " //,icpc_code,nat_code,item_code
         " where valid_flag = '1' and type = '3' and item_name like '%";
    sq += ui->le_key_diag_rule_2->text().trimmed() + "%' order by convert(item_name using gbk) ";

    md_drug_for_rule_constrain->setQuery(sq, pub::db_m);

    ui->tv_drug_for_rule_constrain->setModel(md_drug_for_rule_constrain);

    int width = ui->tv_drug_for_rule_constrain->width();
    pub::setColumnWidth(ui->tv_drug_for_rule_constrain, "0.85", width, 10);
}

void Form_ys_env::on_pb_refresh_rule_constrain_clicked()
{
    sq = "select constrain_name 限制规则, constrain_describe 规则描述, constrain_type, drug_name, condition_code "
         " from reci_ck_drug_constrain le_drug_name_constrain where constrain_name like '%";
    sq += ui->le_key_rule_constrain->text().trimmed() + "%' order by convert(constrain_name using gbk) ";

    md_rule_constrain->setQuery(sq, pub::db_m);

    ui->tv_rule_constrain->setModel(md_rule_constrain);

    int width = ui->tv_rule_constrain->width();
    pub::setColumnWidth(ui->tv_rule_constrain, "0.35^0.5", width, 10);

}

void Form_ys_env::on_pb_save_rule_age_clicked()
{
    if(!check_constrain_status(0))
    {
        return;
    }

    sq = "replace into reci_ck_drug_constrain "
         "(drug_name, constrain_type, condition_code, constrain_name, constrain_describe,oper_code, oper_time)";
    sq += " values(";
    sq += "'" + ui->le_drug_name_constrain->text() + "',";
    sq += "'年龄',";
    sq += "'" + ui->cbb_age_compare->currentText() + " " + ui->le_age->text() + "',";
    sq += "'" +  ui->le_rule_name_constrain->text().trimmed() + "',";
    sq += "'" +  ui->le_rule_describe->text().trimmed() + "',";
    sq += "'" + pub::usr_code + "',";
    sq += "now()";
    sq += ")";
    qDebug()<<"保存年龄限制规则："<<sq;
    if(qrm->exec(sq))
    {
        QMessageBox::information(this, "注意", "规则保存完成！");
    }
    else
    {
        QMessageBox::information(this, "注意", "规则保存失败！\n" + qrm->lastError().text());
    }
}

void Form_ys_env::on_pb_save_rule_gend_clicked()
{
    if(!check_constrain_status(1))
    {
        return;
    }

    sq = "replace into reci_ck_drug_constrain "
         "(drug_name, constrain_type, condition_code, constrain_name,constrain_describe,oper_code, oper_time)";
    sq += " values(";
    sq += "'" + ui->le_drug_name_constrain->text() + "',";
    sq += "'性别',";
    sq += "'" + ui->cbb_constrain_gend->currentText() + "',";
    sq += "'" +  ui->le_rule_name_constrain->text().trimmed() + "',";
    sq += "'" +  ui->le_rule_describe->text().trimmed() + "',";
    sq += "'" + pub::usr_code + "',";
    sq += "now()";
    sq += ")";
    qDebug()<<"保存性别限制规则："<<sq;
    if(qrm->exec(sq))
    {
        QMessageBox::information(this, "注意", "规则保存完成！");
    }
    else
    {
        QMessageBox::information(this, "注意", "规则保存失败！\n" + qrm->lastError().text());
    }
}

bool Form_ys_env::check_constrain_status(int mode)
{
    //
    //mode = 0  age ; mode = 1  gend
    QString rule_name = ui->le_rule_name_constrain->text().trimmed();

    if(rule_name.isEmpty())
    {
        QMessageBox::information(this, "注意", "限制规则名称无效！");
        ui->le_rule_name_constrain->setFocus();
        return false;
    }

    if(mode == 0 && ui->le_age->text().toUInt() < 1)
    {
        QMessageBox::information(this, "注意", "年龄无效！");
        return false;
    }

    if(ui->le_drug_name_constrain->text().isEmpty())
    {
        QMessageBox::information(this, "注意", "未选定有效药品名称！");
        return false;
    }

    sq = "select constrain_name from reci_ck_drug_constrain "
         " where constrain_name =  '" + rule_name + "'";
    qrm->exec(sq);
    if(qrm->next())
    {
        QMessageBox::StandardButton bt;
        bt = QMessageBox::question(this, "注意", "指定的规则名称已经存在，是否覆盖？", QMessageBox::Yes | QMessageBox::No);
        if(bt != QMessageBox::Yes)
        {
            return false;
        }
    }

    return true;
}

void Form_ys_env::on_tv_drug_for_rule_constrain_clicked(const QModelIndex &index)
{
    ui->le_rule_name_constrain->setText(index.siblingAtColumn(0).data().toString());
    ui->le_drug_name_constrain->setText(index.siblingAtColumn(0).data().toString());
}

void Form_ys_env::on_tv_drug_for_rule_constrain_doubleClicked(const QModelIndex &index)
{
    on_tv_drug_for_rule_constrain_clicked(index);
}

void Form_ys_env::on_tv_rule_constrain_clicked(const QModelIndex &index)
{
    ui->le_rule_name_constrain->setText(index.siblingAtColumn(0).data().toString());
    ui->le_rule_describe->setText(index.siblingAtColumn(1).data().toString());
    ui->le_drug_name_constrain->setText(index.siblingAtColumn(3).data().toString());
    QString type = index.siblingAtColumn(2).data().toString();

    if( type == "年龄")
    {
        ui->tb_condition->setCurrentIndex(0);
        QString cond = index.siblingAtColumn(4).data().toString();
        ui->cbb_age_compare->setCurrentText(pub::getStr(cond, " ", 1));
        ui->le_age->setText(pub::getStr(cond, " ", 2));

    }
    else if( type == "性别")
    {
        ui->tb_condition->setCurrentIndex(1);
        ui->cbb_constrain_gend->setCurrentText(index.siblingAtColumn(4).data().toString());
    }
    else
    {

    }
}

void Form_ys_env::on_tv_rule_constrain_doubleClicked(const QModelIndex &index)
{
    on_tv_rule_constrain_clicked(index);
}

void Form_ys_env::on_pb_remove_rule_constrain_clicked()
{
    QString name = ui->le_rule_name_constrain->text().trimmed();
    if(name.isEmpty())
    {
        return;
    }

    QMessageBox::StandardButton bt;

    bt = QMessageBox::question(this, "注意", "确定要删除规则名称: " + name + " ？");
    if(bt != QMessageBox::Yes)
    {
        return ;
    }

    sq = "delete from reci_ck_drug_constrain where constrain_name = '" + name + "'" ;
    if(qrm->exec(sq)){
         QMessageBox::information(this,"注意", "指定的规则名称已经删除！");
    }
    else
    {
        QMessageBox::information(this, "注意", "删除失败！");
    }
}


void Form_ys_env::on_pb_remove_conflict_clicked()
{
    QString conf_name = ui->le_conflict_name->text().trimmed();
    if(conf_name.isEmpty())
    {
        return;
    }

    QMessageBox::StandardButton bt;

    bt = QMessageBox::question(this, "注意", "确定要删除规则名称: " + conf_name + " ？");
    if(bt != QMessageBox::Yes)
    {
        return ;
    }

    sq = "delete from reci_ck_drug_conflict where constrain_name = '" + conf_name + "'" ;
    if(qrm->exec(sq)){
         QMessageBox::information(this,"注意", "指定的规则名称已经删除！");
    }
    else
    {
        QMessageBox::information(this, "注意", "删除失败！");
    }
}

void Form_ys_env::on_pb_diag_gend_clicked()
{
    if(!ui->tvDiag->currentIndex().isValid())
    {
        return;
    }
    QString gend;
    if(ui->rb_diag_gend_M->isChecked())
    {
        gend = "男";
    }
    else if(ui->rb_diag_gend_F->isChecked())
    {
        gend = "女";
    }
    else
    {
        gend = "不限";
    }

    sq = "replace into reci_ck_diag_gend (diag_name, diag_code_icpc, diag_code_nat, gend, oper_code, oper_time)";
    sq += " values(";
    sq += "'" + ui->tvDiag->currentIndex().siblingAtColumn(0).data().toString() + "',";
    sq += "'" + ui->tvDiag->currentIndex().siblingAtColumn(1).data().toString() + "',";
    sq += "'" + ui->tvDiag->currentIndex().siblingAtColumn(2).data().toString() + "',";
    sq += "'" + gend + "',";
    sq += "'" + pub::usr_code + "',";
    sq += " now() ";
    sq += ")";

    qDebug()<<"诊断性别限定："<<sq;

    if(!qrm->exec(sq))
    {
        QMessageBox::information(this,"注意", "保存诊断性别限定发生错误！\n" + qrm->lastError().text());
    }
    else
    {
        QMessageBox::information(this,"注意", "保存成功！");
    }
}

void Form_ys_env::on_tbRemove_3_clicked()
{
    QModelIndex currentindex = ui->tv_dosefom_usage->currentIndex();;

    if(currentindex.row()==-1)
    {
        QMessageBox::warning(this,"注意","未选定有效数据 !");
        return;
    }
    QStandardItem *currentItem = md_form_usage->itemFromIndex(currentindex);

    int parentRow = currentindex.parent().row();

    if(!currentItem->parent())
    {
        //当前选择操作的是父节点
        QMessageBox:: StandardButton result = QMessageBox::warning(NULL, "注意", "是否删除整组数据？",QMessageBox::Yes|QMessageBox::No);
        if(result != QMessageBox::Yes){
            return;
        }

        QString name = currentindex.data().toString();
        sq = "delete from reci_ck_doseform_usage where ";
        if(ui->rbD2I->isChecked())
        {
            sq += " doseform_name = '" + name + "'";
        }else{
            sq += " usage_name = '" + name + "'";
        }
        qrm->exec(sq);
        md_form_usage->removeRow(currentindex.row());

    }
    else
    {
        //子节点
        QString nameParent = currentindex.parent().data().toString();
        QString nameChild = currentindex.data().toString();
        sq = "delete from reci_ck_doseform_usage where ";
        if(ui->rbD2I->isChecked())
        {
            sq += " doseform_name = '" + nameParent + "' and usage_name = '" + nameChild + "'";
        }else{
            sq += " doseform_name = '" + nameChild + "' and usage_name = '" + nameParent + "'";
        }
        qrm->exec(sq);

        QStandardItem *parent = currentItem->parent();
        parent->removeRow(currentindex.row());
        if(parent->rowCount()<1)
        {
            //删除之后，父节点再无其它子节点，父节点同时删除
            md_form_usage->removeRow(parentRow);
        }
    }
}

void Form_ys_env::on_cbb_dept_currentIndexChanged(const QString &arg1)
{
    if(!initial_finished)
    {
        return;
    }

    int pos = pub::searchStr(depts_code, "^", arg1);
    dept_constrain = pub::getStr(depts_code, "^", pos + 1);

    sq = "select name from com_dict_com where dic_type = '执行科室' and dept_code = '"
            +dept_constrain+"' order by code";

    fillCombo(ui->cbbExecDept, sq);//执行科室

}


void Form_ys_env::on_pb_clear_conflict_items_clicked()
{
    md_drug_in_rule_conflict->setQuery(NULL);
    qrm->exec("delete from tmp_drug_conflict");
    ui->le_conflict_name->clear();
}

void Form_ys_env::on_tab_recipe_check_currentChanged(int index)
{
    if(index == 4)
    {
        sq = "select name,code from com_dictionary where  type ='MINFEE' "
             " and valid_state = '1' order by code "; //and code not in('001', '002', '003')

        fee_name_code = pub::fillCombo(ui->cbb_fee_type, sq , -1, qrot);//

        //ui->cbb_fee_type->addItem("默认");
        //fee_name_code.append("^默认^");

        sq = " select dept_name, dept_code from com_department "
             " where valid_state = '1' "
             " order by dept_name";

        dept_name_code = pub::fillCombo(ui->cbb_oper_dept, sq, -1, qrot);

        ui->cbb_oper_dept->addItem("默认");
        dept_name_code.append("^默认^");

        display_reci_days();
    }
}

void Form_ys_env::display_reci_days()
{
    ui->cbb_reg_mode->setCurrentIndex(0);
    ui->cbb_oper_dept->setCurrentIndex(0);
    ui->cbb_fee_type->setCurrentIndex(0);
    ui->le_reci_single->clear();
    ui->le_reci_aux->clear();

    sq = "select pact_type 挂号方式, dept_code 诊室, fee_type 收费类别, item_name 项目名称,  "
         " days_count_single 单处方限量, days_count_current 附加限量,reci_type 处方类型 "
         " from reci_ck_days "
         " order by item_name,fee_type, dept_code,pact_type";

    md_reci_ck_days->setQuery(sq, pub::db_m);
    ui->tv_reci_ck->setModel(md_reci_ck_days);
    int w = ui->tv_reci_ck->width();
    pub::setColumnWidth(ui->tv_reci_ck, "0.05^0.1^0.1^0.2^0.15^0.15^0.15^", w);

}

void Form_ys_env::on_rb_tr_diag_clicked()
{
    on_rb01_clicked();
}

void Form_ys_env::on_rb_tr_symptom_clicked()
{
    on_rb01_clicked();
}

void Form_ys_env::on_le_key_diag_returnPressed()
{
    QString key = ui->le_key_diag->text().trimmed();

    on_pb_search_diag_clicked();
}

void Form_ys_env::on_pb_search_diag_clicked()
{
    QString key = ui->le_key_diag->text().trimmed();

    sq = "select nat_code icd编码, item_name 诊断名称 from com_dict_icpc where type = '2' and "
         " instr(dept_code, '%1' ) > 0 and item_name like '%%2%' "
         " order by convert(item_name using gbk)";

    sq = sq.arg(dept_constrain).arg(key);

    md_diag_med->setQuery(sq, pub::db_m);
    ui->tv_diag_med->setModel(md_diag_med);
    pub::setColumnWidth(ui->tv_diag_med, "0.4^0.4", ui->tv_diag_med->width());
}

void Form_ys_env::on_le_key_diag_tr_returnPressed()
{
    QString key = ui->le_key_diag_tr->text().trimmed();

    on_pb_search_diag_tr_clicked();
}

void Form_ys_env::on_pb_search_diag_tr_clicked()
{
    QString key = ui->le_key_diag_tr->text().trimmed();

    sq = "select nat_code icd编码, item_name 诊断名称 from com_dict_icpc where type = '8' and "
         " instr(dept_code, '%1' ) > 0 and item_name like '%%2%' "
         " order by convert(item_name using gbk)";

    sq = sq.arg(dept_constrain).arg(key);

    md_diag_tr->setQuery(sq, pub::db_m);
    ui->tv_diag_tr->setModel(md_diag_tr);
    pub::setColumnWidth(ui->tv_diag_tr, "0.4^0.4", ui->tv_diag_tr->width());
}

void Form_ys_env::on_le_key_symptom_tr_returnPressed()
{
    QString key = ui->le_key_symptom_tr->text().trimmed();

    on_pb_search_symptom_tr_clicked();
}

void Form_ys_env::on_pb_search_symptom_tr_clicked()
{
    QString key = ui->le_key_symptom_tr->text().trimmed();

    sq = "select nat_code icd编码, item_name 证候名称 from com_dict_icpc where type = '9' and "
         " instr(dept_code, '%1' ) > 0 and item_name like '%%2%' "
         " order by convert(item_name using gbk)";

    sq = sq.arg(dept_constrain).arg(key);

    md_symptom_tr->setQuery(sq, pub::db_m);
    ui->tv_symptom_tr->setModel(md_symptom_tr);
    pub::setColumnWidth(ui->tv_symptom_tr, "0.4^0.4", ui->tv_symptom_tr->width());
}

void Form_ys_env::on_le_key_relate_med_tr_returnPressed()
{
    QString key = ui->le_key_relate_med_tr->text().trimmed();

    on_pb_search_med_tr_clicked();
}

void Form_ys_env::on_pb_search_med_tr_clicked()
{
    if(dept_constrain.isEmpty())
    {
        QMessageBox::information(this, "注意", "未指定诊室！");
        return;
    }
    QString key = ui->le_key_relate_med_tr->text().trimmed();

    sq = "select med_diag_code 西医编码, med_diag_name 西医诊断, "  //0,1
         " tr_diag_code 中医编码, tr_diag_name 中医诊断, "//2,3
         " tr_symptom_code 证候编码, tr_symptom_name 中医证候 ,"//4,5
         " med_diag_base, tr_diag_base, atinc, tr_diag_symptom ,"//6,7,8,9
         " patient_describe, med_now, person_hist, "   //10,11,12
         " tr_similar_syndrom, tr_treatment, "  //13,14
         " hist_symptom, allergy_hist,"   //15,16 既往史，过敏史
         " family_hist, menstr_hist, medical_advice"  //17,19 家族史，月经史，医嘱
         " from com_diag_med_tr where "
         " dept_code = '%1' and %2 "
         " order by convert ( %3 using gbk)";

    QString cond2,cond3;
    if(ui->rb_ord_med->isChecked())
    {
        cond2 = "med_diag_name like '%" + key + "%'";
        cond3 = "med_diag_name";
    }
    else
    {
        cond2 = "tr_diag_name like '%" + key + "%'";
        cond3 = "tr_diag_name";
    }

    sq = sq.arg(dept_constrain).arg(cond2).arg(cond3);

    qDebug()<<"显示中西医诊断对照关联 ： "<<sq;

    md_relate_med_tr->setQuery(sq, pub::db_m);
    ui->tv_relate_med_tr->setModel(md_relate_med_tr);
    pub::setColumnWidth(ui->tv_relate_med_tr, "0.15^0.15^0.15^0.15^0.15^0.15^0^0^0^0^0^0^0^0^0^0^0^0^0^0^0",
                        ui->tv_relate_med_tr->width());

    ui->pt_base->setPlainText("【主诉】\n【现病史】\n【既往史】\n【过敏史】\n【个人史】\n【月经史】\n【家族史】\n【体格检查】"
                              "\n【中医查体】\n【辨证依据】\n【中医类证鉴别】\n【治则】\n【医嘱】");
}

void Form_ys_env::on_tb_remove_med_tr_clicked()
{
    if(!ui->tv_relate_med_tr->currentIndex().isValid())
    {
        QMessageBox::information(this, "注意", "未选定有效数据行！");
        return;
    }

    QMessageBox::StandardButton bt;
    bt = QMessageBox::question(this, "注意", "是否删除当前对照关联？");
    if(bt != QMessageBox::Yes)
    {
        return;
    }
    sq = "delete from com_diag_med_tr where "
         " atinc = " + ui->tv_relate_med_tr->currentIndex().siblingAtColumn(8).data().toString();
    qDebug()<<"删除中西医诊断对照关联:"<<sq;
    qrm->exec(sq);

    on_pb_search_med_tr_clicked();

    med_tr_relate.clear();
}

void Form_ys_env::on_tb_add_med_tr_clicked()
{
    if(dept_constrain.isEmpty() )
    {
        QMessageBox::information(this, "注意", "未指定工作诊室！");
        return;
    }

    QString base = ui->pt_base->toPlainText();

    base.replace("】","【");
    base.replace("\n","");

    if(base.count("【") != 26)
    {
        QMessageBox::information(this, "注意", "原始字串中的分隔符错误！");
        return;
    }
    qDebug()<<base;
    QStringList base_list = base.split("【");
    if(   base_list[1] != "主诉"
          || base_list[3] != "现病史"
          || base_list[5] != "既往史"
          || base_list[7] != "过敏史"
          || base_list[9] != "个人史"
          || base_list[11] != "月经史"
          || base_list[13] != "家族史"
          || base_list[15] != "体格检查"
          || base_list[17] != "中医查体"
          || base_list[19] != "辨证依据"
          || base_list[21] != "中医类证鉴别"
          || base_list[23] != "治则"
          || base_list[25] != "医嘱"
          )
    {
        QMessageBox::information(this, "注意", "原始字串内容缺失或顺序错误！");
        return;
    }

    QString patient_describe = base_list[2]; //主诉
    QString med_now = base_list[4]; //现病史
    QString hist_symptom = base_list[6]; //既往史
    QString allergy_hist = base_list[8]; //过敏史
    QString person_hist = base_list[10]; //个人史
    QString menstr_hist = base_list[12]; //月经史
    QString family_hist = base_list[14]; //家族史
    QString body_chk = base_list[16]; //体格检查
    QString body_chk_tr = base_list[18]; //中医查体
    QString syndrom_basis_tr = base_list[20]; //辨证依据
    QString similar_syndrom_tr = base_list[22]; //中医类证鉴别
    QString treatment_tr = base_list[24]; //治则
    QString medical_advice = base_list[26]; //医嘱

    //异或条件判断，同时有或同时无 为允许，只有一个为禁止

    if(med_tr_relate["med_diag_code"].isEmpty() ^ body_chk.isEmpty())
    {
        qDebug()<<"med_diag_code, diag_base is " <<med_tr_relate["med_diag_code"] << body_chk;
        QMessageBox::information(this, "注意", "西医诊断和体格检查应同时出现！");
        return;
    }

    if(med_tr_relate["tr_diag_code"].isEmpty() ^ body_chk_tr.isEmpty() )
    {
        QMessageBox::information(this, "注意", "中医诊断和中医查体应同时出现！");
        return;
    }

    if(med_tr_relate["tr_diag_code"].isEmpty() ^ treatment_tr.isEmpty() )
    {
        QMessageBox::information(this, "注意", "中医诊断和治则应同时出现！");
        return;
    }

    if(med_tr_relate["tr_symptom_code"].isEmpty() ^ syndrom_basis_tr.isEmpty()
            || med_tr_relate["tr_symptom_code"].isEmpty() ^ similar_syndrom_tr.isEmpty() )
    {
        QMessageBox::information(this, "注意", "中医证候和辩证依据、类证鉴别应同时出现！");
        return;
    }

    if(med_tr_relate["tr_diag_code"].isEmpty() ^ med_tr_relate["tr_symptom_code"].isEmpty())
    {
        QMessageBox::information(this, "注意", "中医诊断与证候应同时出现！");
        return;
    }

    if(med_tr_relate["med_diag_code"].isEmpty()
            && med_tr_relate["tr_symptom_code"].isEmpty()
            && med_tr_relate["tr_diag_code"].isEmpty()
            )
    {
        QMessageBox::information(this, "注意", "中医诊断与西医诊断不可以同时为空！");
        return;
    }

    sq = " replace into com_diag_med_tr ("
         " med_diag_code, med_diag_name, "  //1,2 西医诊断代码名称
         " med_diag_base, " //3 西医诊断依据
         " tr_diag_code, tr_diag_name, " //4,5 中医诊断代码名称
         " tr_symptom_code, tr_symptom_name," //6,7 中医证候代码名称
         " tr_diag_base, tr_diag_symptom, "//8,9 中医诊断依据，中医辩证
         " dept_code, "//10 诊室代码
         " oper_date, oper_code ," //11
         " patient_describe, med_now, person_hist,"//12,13,14 主䜣，现病史， 个人史
         " tr_similar_syndrom, tr_treatment, "//15,16 /中医类证鉴别 , //治则
         " hist_symptom, allergy_hist," //17,18 既往史，过敏史
         " family_hist, menstr_hist, medical_advice"  //19,21 家族史，月经史，医嘱
         " ) values ("
         " '%1', '%2', '%3', '%4', '%5', " //
         " '%6', '%7', '%8', '%9', "
         " '%10', curdate(), "
         " '%11', '%12', '%13', '%14', '%15', '%16',"
         " '%17', '%18', '%19', '%20', '%21'"
         " )";
    sq = sq.arg(med_tr_relate["med_diag_code"]);  //1,2 西医诊断代码名称
    sq = sq.arg(med_tr_relate["med_diag_name"]);
    sq = sq.arg(body_chk);  //3
    sq = sq.arg(med_tr_relate["tr_diag_code"]);  //4,5 中医诊断代码名称
    sq = sq.arg(med_tr_relate["tr_diag_name"]);
    sq = sq.arg(med_tr_relate["tr_symptom_code"]);  //6,7 中医证候代码名称
    sq = sq.arg(med_tr_relate["tr_symptom_name"]);
    sq = sq.arg(body_chk_tr);  //8,9 中医诊断依据，中医辩证
    sq = sq.arg(syndrom_basis_tr);  //
    sq = sq.arg(dept_constrain);  //10 诊室代码
    sq = sq.arg(pub::usr_code);  //11

    sq = sq.arg(patient_describe);  //12
    sq = sq.arg(med_now);  //13
    sq = sq.arg(person_hist);  //14

    sq = sq.arg(similar_syndrom_tr);  //15
    sq = sq.arg(treatment_tr);  //16

    sq = sq.arg(hist_symptom);  //17
    sq = sq.arg(allergy_hist);  //18

    sq = sq.arg(family_hist);  //19
    sq = sq.arg(menstr_hist);  //20
    sq = sq.arg(medical_advice);  //21

    qDebug()<<"插入西医中医诊断关联："<<sq;
    if(!qrm->exec(sq))
    {
        QMessageBox::information(this, "注意", "插入中西医诊断关联失败！\n" + qrm->lastError().text());
        return;
    }
    else
    {
        QMessageBox::information(this, "注意", "诊断模版信息保存完成！");
    }

    on_pb_search_med_tr_clicked();

    med_tr_relate.clear();
}

void Form_ys_env::on_tv_relate_med_tr_clicked(const QModelIndex &index)
{

    med_tr_relate["med_diag_code"] = index.siblingAtColumn(0).data().toString();
    med_tr_relate["med_diag_name"] = index.siblingAtColumn(1).data().toString();
    med_tr_relate["tr_diag_code"] = index.siblingAtColumn(2).data().toString();
    med_tr_relate["tr_diag_name"] = index.siblingAtColumn(3).data().toString();
    med_tr_relate["tr_symptom_code"] = index.siblingAtColumn(4).data().toString();
    med_tr_relate["tr_symptom_name"] = index.siblingAtColumn(5).data().toString();
    med_tr_relate["med_diag_base"] = index.siblingAtColumn(6).data().toString();
    med_tr_relate["tr_diag_base"] = index.siblingAtColumn(7).data().toString();
    med_tr_relate["tr_diag_symptom"] = index.siblingAtColumn(9).data().toString();
    med_tr_relate["patient_describe"] = index.siblingAtColumn(10).data().toString();
    med_tr_relate["med_now"] = index.siblingAtColumn(11).data().toString();
    med_tr_relate["person_hist"] = index.siblingAtColumn(12).data().toString();
    med_tr_relate["tr_similar_syndrom"] = index.siblingAtColumn(13).data().toString();
    med_tr_relate["tr_treatment"] = index.siblingAtColumn(14).data().toString();
    med_tr_relate["hist_symptom"] = index.siblingAtColumn(15).data().toString();
    med_tr_relate["allergy_hist"] = index.siblingAtColumn(16).data().toString();
    med_tr_relate["family_hist"] = index.siblingAtColumn(17).data().toString();
    med_tr_relate["menstr_hist"] = index.siblingAtColumn(18).data().toString();
    med_tr_relate["medical_advice"] = index.siblingAtColumn(19).data().toString();


    //ui->pt_diag_base->setPlainText(med_tr_relate["med_diag_base"]);
    //ui->pt_diag_base_tr->setPlainText(med_tr_relate["tr_diag_base"]);
    //ui->pt_diag_symptom_tr->setPlainText(med_tr_relate["tr_diag_symptom"]);

    QString base = "【主诉】";
    base.append(med_tr_relate["patient_describe"]);
    base.append("\n");
    base.append("【现病史】");
    base.append(med_tr_relate["med_now"]);
    base.append("\n");

    base.append("【既往史】");
    base.append(med_tr_relate["hist_symptom"]);
    base.append("\n");
    base.append("【过敏史】");
    base.append(med_tr_relate["allergy_hist"]);
    base.append("\n");
    base.append("【个人史】");
    base.append(med_tr_relate["person_hist"]);
    base.append("\n");
    base.append("【月经史】");
    base.append(med_tr_relate["menstr_hist"]);
    base.append("\n");
    base.append("【家族史】");
    base.append(med_tr_relate["family_hist"]);
    base.append("\n");


    base.append("【体格检查】");
    base.append(med_tr_relate["med_diag_base"]);
    base.append("\n");
    base.append("【中医查体】");
    base.append(med_tr_relate["tr_diag_base"]);
    base.append("\n");
    base.append("【辨证依据】");
    base.append(med_tr_relate["tr_diag_symptom"]);
    base.append("\n");
    base.append("【中医类证鉴别】");
    base.append(med_tr_relate["tr_similar_syndrom"]);
    base.append("\n");
    base.append("【治则】");
    base.append(med_tr_relate["tr_treatment"]);
    base.append("\n");
    base.append("【医嘱】");
    base.append(med_tr_relate["medical_advice"]);

    //base.append("^");



    ui->pt_base->setPlainText(base);

    QModelIndex idx;
    QString code_med = index.siblingAtColumn(0).data().toString();
    QString code_tr = index.siblingAtColumn(2).data().toString();
    QString code_symp = index.siblingAtColumn(4).data().toString();

    int rows = md_diag_med->rowCount();
    for(int i = 0; i< rows; i++)
    {
        idx = md_diag_med->index(i, 0);
        if(idx.siblingAtColumn(0).data().toString() == code_med)
        {
            ui->tv_diag_med->setCurrentIndex(idx);
            break;
        }
    }

    rows = md_diag_tr->rowCount();
    for(int i = 0; i< rows; i++)
    {
        idx = md_diag_tr->index(i, 0);
        if(idx.siblingAtColumn(0).data().toString() == code_tr)
        {
            ui->tv_diag_tr->setCurrentIndex(idx);
            break;
        }
    }

    rows = md_symptom_tr->rowCount();
    for(int i = 0; i< rows; i++)
    {
        idx = md_symptom_tr->index(i, 0);
        if(idx.siblingAtColumn(0).data().toString() == code_symp)
        {
            ui->tv_symptom_tr->setCurrentIndex(idx);
            break;
        }
    }

}

void Form_ys_env::on_tv_relate_med_tr_doubleClicked(const QModelIndex &index)
{
    on_tv_relate_med_tr_clicked(index);
}

void Form_ys_env::on_tv_diag_med_doubleClicked(const QModelIndex &index)
{
    on_tv_diag_med_clicked(index);
}

void Form_ys_env::on_tv_diag_med_clicked(const QModelIndex &index)
{
    med_tr_relate["med_diag_code"] = index.siblingAtColumn(0).data().toString();
    med_tr_relate["med_diag_name"] = index.siblingAtColumn(1).data().toString();
}

void Form_ys_env::on_tv_diag_tr_doubleClicked(const QModelIndex &index)
{
    on_tv_diag_tr_clicked(index);
}

void Form_ys_env::on_tv_diag_tr_clicked(const QModelIndex &index)
{
    med_tr_relate["tr_diag_code"] = index.siblingAtColumn(0).data().toString();
    med_tr_relate["tr_diag_name"] = index.siblingAtColumn(1).data().toString();
}

void Form_ys_env::on_tv_symptom_tr_doubleClicked(const QModelIndex &index)
{
    on_tv_symptom_tr_clicked(index);
}

void Form_ys_env::on_tv_symptom_tr_clicked(const QModelIndex &index)
{
    med_tr_relate["tr_symptom_code"] = index.siblingAtColumn(0).data().toString();
    med_tr_relate["tr_symptom_name"] = index.siblingAtColumn(1).data().toString();
}

void Form_ys_env::on_tabWidget_currentChanged(int index)
{
    if(dept_constrain.isEmpty())
    {
        return;
    }

    if(index == 4) //诊断对应关系
    {

        ui->le_key_diag->clear();
        ui->le_key_diag_tr->clear();
        ui->le_key_symptom_tr->clear();
        ui->le_key_relate_med_tr->clear();

        on_pb_search_diag_tr_clicked();
        on_pb_search_diag_clicked();
        on_pb_search_symptom_tr_clicked();
        on_pb_search_med_tr_clicked();

    }
}
//


void Form_ys_env::on_pb_dic_type_clicked()
{
    if(ui->pb_dic_type->text() == "新增")
    {
        //初始状态
        ui->pb_dic_type->setText("保存");
        ui->pbAdd->setEnabled(false);
        ui->pbDel->setEnabled(false);
        ui->leDict->setReadOnly(false);
        ui->gb_new_dict->setVisible(true);
    }
    else
    {
        QString new_type = ui->leDict->text().trimmed();
        if(new_type.isEmpty())
        {
            QMessageBox::information(this, "注意", "字典名不可以为空！");
            return;
        }

        QString mark, dic_type;

        if(ui->cbb_range->currentText() == "全院")
        {
            mark = "all";
        }
        else
        {
            mark = "dept";
        }

        if(ui->rbDoct->isChecked())
        {
            dic_type = "doct_dic";
        }
        else
        {
            dic_type = "com_dic";
        }

        sq = "delete from com_dict_com where"
             " dic_type in ('doct_dic', 'com_dic')"
             " and name = '" + new_type + "' ";

        qrm->exec(sq);

        sq = "insert into com_dict_com "
             "(code, oper_time, valid_flag, oper_code, dic_type, name, mark)"
             " values( '0',curdate(),'1','"
                + pub::usr_code +"','"
                + dic_type + "','"
                + new_type + "','"
                + mark + "'"
             ")";

        qrm->exec(sq);


        ui->pb_dic_type->setText("新增");
        ui->pbAdd->setEnabled(true);
        ui->pbDel->setEnabled(true);
        ui->leDict->setReadOnly(true);
        ui->gb_new_dict->setVisible(false);

        on_pbFresh_clicked();
    }

}

void Form_ys_env::on_tv_reci_ck_doubleClicked(const QModelIndex &index)
{
    on_tv_reci_ck_clicked(index);
}

void Form_ys_env::on_tv_reci_ck_clicked(const QModelIndex &index)
{
    QString mode = index.siblingAtColumn(0).data().toString();
    QString dept = index.siblingAtColumn(1).data().toString();
    QString fee = index.siblingAtColumn(2).data().toString();
    QString item_name = index.siblingAtColumn(3).data().toString();
    QString single = index.siblingAtColumn(4).data().toString();
    QString aux = index.siblingAtColumn(5).data().toString();

    ui->cbb_reg_mode->setCurrentText(mode);
    ui->cbb_oper_dept->setCurrentText(dept);
    ui->cbb_fee_type->setCurrentText(fee);
    ui->le_reci_single->setText(single);
    ui->le_reci_aux->setText(aux);
    ui->le_item_code->setText(item_name);


}

void Form_ys_env::on_pb_save_reci_days_clicked()
{

    if(ui->le_reci_single->text().toInt() < 1
            || ui->le_reci_aux->text().toInt() < 1
            )
    {
        QMessageBox::information(this, "注意", "处方天数限定数据无效！");
        return;
    }


        QString mode = ui->cbb_reg_mode->currentText();
        QString fee = ui->cbb_fee_type->currentText();
        QString dept = ui->cbb_oper_dept->currentText();

    QString reci;
    if(fee == "西药费" || fee == "中成药" || fee == "中草药" )
    {
        reci = "drug";
    }
    else
    {
        reci = "undrug";
    }

    reci_ck_item_name = ui->le_item_code->text().trimmed();

    if(reci_ck_item_name.isEmpty())
    {
        reci_ck_item_name = "ALL";
    }

    sq = "replace into reci_ck_days "
         " (pact_type, fee_type, dept_code,reci_type, "
         " days_count_single, days_count_current ,item_code,item_name) "
         " values ( '%1', '%2', '%3', '%4', %5, %6,'%7','%8') ";

    sq = sq.arg(mode)
            .arg(fee)
            .arg(dept)
            .arg(reci)
            .arg(ui->le_reci_single->text())
            .arg(ui->le_reci_aux->text())
            .arg(reci_ck_item_code)
            .arg(reci_ck_item_name);

    qDebug()<<"增加处方天数限定记录："<<sq<<"\n";

    if(qrm->exec(sq))
    {
        //QMessageBox::information(this, "注意", "处方天数限定修改完成！");
        display_reci_days();
    }
    else
    {
        QMessageBox::information(this, "注意", "处方天数限定保存失败！");
    }

}

void Form_ys_env::on_pb_reci_remove_clicked()
{

    QMessageBox::StandardButton bt;
    bt = QMessageBox::question(this, "注意", "确认要删掉当前的限定记录？");
    if(bt != QMessageBox::Yes)
    {
        return;
    }

    sq = "delete from reci_ck_days where "
         " pact_type = '%1' and fee_type = '%2' and  dept_code = '%3'";

    sq = sq.arg(ui->cbb_reg_mode->currentText())
            .arg(ui->cbb_fee_type->currentText())
            .arg(ui->cbb_oper_dept->currentText());

    qDebug()<<"删除处方天数限定记录："<<sq<<"\n";

    if(qrm->exec(sq))
    {
        //QMessageBox::information(this, "注意", "处方天数限定修改完成！");
        display_reci_days();
    }
    else
    {
        QMessageBox::information(this, "注意", "处方天数限定保存失败！");
    }
}

void Form_ys_env::on_tb_search_item_clicked()
{
    if(ui->le_item_code->text().trimmed().isEmpty())
    {
        return;
    }
    reci_ck_item_name = "";
    reci_ck_item_code = "";
    QString fee = ui->cbb_fee_type->currentText();

    //药品
    if(fee == "西药费" || fee == "中成药" || fee == "中草药" )
    {

        sq = "select BASE.trade_name 药品名称, BASE.specs 规格, "
             "BASE.drug_code 药品编码 "
             " from pha_com_baseinfo base"
             " where BASE.valid_state = '1' "
             " and ( BASE.spell_code like '%"
                + ui->le_item_code->text().trimmed().toUpper()
                + "%' or BASE.trade_name like '%"
                + ui->le_item_code->text().trimmed() + "%')" ;

    }
    else
    {
        sq = "select item_name, 'specs', item_code"
             " from fin_com_undruginfo where valid_state = '1' and "
             "  ( spell_code like ";
        sq += "'%"+ui->le_item_code->text().trimmed().toUpper();
        sq += "%' or item_name like '%"+ui->le_item_code->text().trimmed()+"%')";
    }

    qDebug()<<"项目检索："<<sq<<"\n";

    mdPop->setQuery( sq , pub::db_o);

    if(mdPop->rowCount() == 0)
    {
        QMessageBox::information(this, "注意", "指定关键字找不到有效的项目！");
        return;
    }
    else if(mdPop->rowCount() == 1)
    {
        reci_ck_item_name = mdPop->record(0).value(0).toString();
        reci_ck_item_code = mdPop->record(0).value(2).toString();
    }
    else
    {

        dlgp->setDisplay(*mdPop,QRect(300, 200, 600, 500),"","0.35^0.25^0.3^0");//用 宽度比例为0 实现列隐藏

        popRetStr = "";
        dlgp->setModal(true);
        dlgp->exec();

        popRetStr = dlgp->retStr();
        if(popRetStr.isEmpty())
        {
            return;
        }
        reci_ck_item_name = pub::getStr(popRetStr, "^", 1);
        reci_ck_item_code = pub::getStr(popRetStr, "^", 3);
    }

    ui->le_item_code->setText(reci_ck_item_name);
}

void Form_ys_env::on_le_item_code_returnPressed()
{
    on_tb_search_item_clicked();
}
